我有一个从.properties文件中读取值的需求
我的属性文件test.properties
内容
file=jaguar8
extension=txt
path=c:\Program Files\AC
从上面的文件中,我需要获取jaguar
或=
之后的任何内容
请帮帮我。谢谢
发布于 2011-10-10 13:10:31
For /F "tokens=1* delims==" %%A IN (test.properties) DO (
IF "%%A"=="file" set file=%%B
)
echo "%file%"
希望这能有所帮助
发布于 2013-02-22 21:06:29
@echo off
FOR /F "tokens=1,2 delims==" %%G IN (test.properties) DO (set %%G=%%H)
echo %file%
echo %extension%
echo %path%
请注意,%%H之后没有空格。否则,这会导致在文件路径后附加一个空格,并且当属性文件中的变量作为文件path.Struggled的一部分使用数小时时,将导致文件找不到错误。
发布于 2015-11-26 02:24:01
支持注释的解决方案(# style)。有关说明,请参阅代码中的注释。
test.properties:
# some comment with = char, empty line below
#invalid.property=1
some.property=2
some.property=3
# not sure if this is supported by .properties syntax
text=asd=f
properties-read.bat:
@echo off
rem eol stops comments from being parsed
rem otherwise split lines at the = char into two tokens
for /F "eol=# delims== tokens=1,*" %%a in (test.properties) do (
rem proper lines have both a and b set
rem if okay, assign property to some kind of namespace
rem so some.property becomes test.some.property in batch-land
if NOT "%%a"=="" if NOT "%%b"=="" set test.%%a=%%b
)
rem debug namespace test.
set test.
rem do something useful with your vars
rem cleanup namespace test.
rem nul redirection stops error output if no test. var is set
for /F "tokens=1 delims==" %%v in ('set test. 2^>nul') do (
set %%v=
)
set test.
的输出(见上):
test.some.property=3
test.text=asd=f
最重要的部分是:
使用eol
和delims
选项设置for
代码,使用
if
-checks设置变量%%a
和%%b
。在for
-loop中如何处理变量和它的值当然取决于您-赋值给一些带前缀的变量只是一个例子。命名空间方法避免了任何其他全局变量被覆盖。例如,如果您在.properties文件中定义了类似appdata
的内容。
我用它去掉了一个额外的config.bat,取而代之的是对java应用程序和一些支持的批处理文件使用一个.properties文件。
适用于我,但肯定不是这里涵盖了所有的边缘情况,所以欢迎改进!
https://stackoverflow.com/questions/7708681
复制相似问题