相对目录处理方法备忘

一个项目往往除了包含程序文件外,还包含一些资源文件, 我们需要把这些程序和资源都打包到一个文件夹中, 并创建一个启动脚本来启动程序,并为程序指定资源位置,这时候就需要使用相对目录

Windows下的目录设置

windows下bat文件获取当前目录, 以及将bat所在目录设置为当前目录的方法

@echo off
echo %cd%
echo %~dp0
cd /d %~dp0
echo %cd%

将以上脚本存为C:\tmp\test\path.bat, 在C:\tmp\test目录下执行test\path.bat,运行结果为:

C:\tmp
C:\tmp\test\
C:\tmp\test

Linux下的目录设置

#!/bin/bash
pwd
basepath=$(cd `dirname $0`; pwd)
pwd
echo $basepath
cd $basepath
pwd

将以上脚本存为/tmp/test/path.sh, 在/tmp目录下执行test/path.sh,运行结果为:

/tmp
/tmp
/tmp/test
/tmp/test

Springboot指定静态资源目录

假设启用脚本、jar文件、html目录平级, 而网页文件放在html目录中,在windows下启动脚本如下

@echo off
cd /d %~dp0
java -jar xxx.jar --spring.resources.static-locations=file:%cd%\html

在Linux下启动脚本如下:

#!/bin/bash
basepath=$(cd `dirname $0`; pwd)
cd $basepath
java -jar xxx.jar --spring.resources.static-locations=file:${basepath}/html