java System.getProperty 为定义的属性返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4597796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
System.getProperty returns null for defined property
提问by Derek
I have a property TOOLS_DIR
that i exported in bash
我有一个TOOLS_DIR
我在 bash 中导出的属性
I have the following line in my java file:
我的java文件中有以下行:
String toolsDir = System.getProperty("TOOLS_DIR");
Why is this returning null? is the a compatibility issue with linux or something?
为什么这返回空?是与linux的兼容性问题还是什么?
回答by Konstantin Komissarchik
Environment variables and properties aren't the same thing. If you want to pass in an environment variable as property you have to add the following to your java invocation:
环境变量和属性不是一回事。如果要将环境变量作为属性传入,则必须将以下内容添加到 Java 调用中:
-DTOOLS_DIR=$TOOLS_DIR
Alternatively, you can use System.getEnv()
或者,您可以使用 System.getEnv()
回答by David J. Liszewski
Java system properties have nothing to do with shell environment variables.
Java 系统属性与 shell 环境变量无关。
You can assign a java system property when you invoke the virtual machine, for example:
您可以在调用虚拟机时分配一个 java 系统属性,例如:
java -DTOOLS_DIR=/somewhere org.example.MyClass
回答by robert_x44
Try this instead:
试试这个:
String toolsDir = System.getenv("TOOLS_DIR");
The getProperty(...) method returns java vm properties (like user.dir, java.version). The getenv(...) method is for environment variables.
getProperty(...) 方法返回 java vm 属性(如 user.dir、java.version)。getenv(...) 方法用于环境变量。