本文要实现以下功能
在一个启动脚本中,需要读取指定的配置文件(properties格式),读取指定的值后,传递给相应的命令来执行,以实现可配置参数和参数统一配置的目的(避免在不同的文件中修改参数)
以下为关键的读取配置文件的批处理代码,其中使用了for循环命令:
rem 读取指定文件下的指定参数的值,并将值设制到参数中 //传入的参数 %1:哪个配置文件 %2:读取的key值 //付出 将对应key的值绑定在key上,即set key=value set b=- setlocal EnableDelayedExpansion set a=- for /f "delims== tokens=1,2" %%i in (%1) do ( set a=%%i call :trim a if !a!==%2 ( set b=%%j call :trim b break ) ) endlocal & set b=%b% set %2=%b% goto :eof
在以上批处理命令中,用到了trim函数,即一个去除一个字符串两端空格的函数。值得注意的是,由于使用了setlocal,使得要将里面的b值传递到外层的b值,在endlocal处使用了 & 符号。即endlocal & set b=%b%,这一句代码,必须连在一行,无论是将endlocal提上一行或者提下一行,均不能实现指定的效果。具体原因尚未得知。
其它的就是如何进行trim,在如何在批处理命令中调用了。trim函数如下所示:
:trim if "!%1:~0,1!"==" " (set %1=!%1:~1!&&goto trim) if "!%1:~0,1!"==" " (set %1=!%1:~1!&&goto trim) if "!%1:~-1!"==" " (set %1=!%1:~0,-1!&&goto trim) if "!%1:~-1!"==" " (set %1=!%1:~0,-1!&&goto trim) goto :eof
在批处理中调用,的代码:
call readProperty.bat config.properties jvmmin call readProperty.bat config.properties jvmmax jre\bin\java -Xms%jvmmin% -Xmx%jvmmax%
以上就是完整的读取配置文件并设置命令参数的命令了。
关于,如何读取指定的配置文件值,在笔者的提问界面:http://topic.csdn.net/u/20111008/16/02f292d3-1ca8-4504-9463-e66fa2526552.html 中。Forever_Young提出了另一种解法,即使用findstr,如下所示:
for /f %%i in ('findstr /b /i "%1=" xxxxx.txt') do (set "%%i")
试了一下,果然有用,特此感谢。
转载请标明出处:i flym
本文地址:https://www.iflym.com/index.php/java-programe/201110090002.html