如何在Java中读取配置文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16273174/
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
How to read a configuration file in Java
提问by devsda
I am doing a project to build thread pooled web server
, in which I have to set
我正在做一个项目来构建thread pooled web server
,我必须在其中设置
- the port number on which server listens.
- How many threads are there in thread pool
- Absolute Path of the root directory, and so many points.
- 服务器侦听的端口号。
- 线程池中有多少线程
- 根目录的绝对路径,等等。
One way is to hard code all these variables in the code, that I did. But professionally it is not good.
一种方法是在代码中对所有这些变量进行硬编码,我就是这样做的。但从专业上来说并不好。
Now, I want to make one configuration file, in which I put all these data, and at the run time my code fetches these.
现在,我想制作一个配置文件,在其中放置所有这些数据,并在运行时我的代码获取这些数据。
How can I make configuration file for the above task ?
如何为上述任务制作配置文件?
回答by MadProgrammer
It depends.
这取决于。
Start with Basic I/O, take a look at Properties, take a look at Preferences APIand maybe even Java API for XML Processingand Java Architecture for XML Binding
从Basic I/O开始,看看Properties,看看Preferences API甚至是Java API for XML Processing和Java Architecture for XML Binding
And if none of those meet your particular needs, you could even look at using some kind of Database
如果这些都不能满足您的特定需求,您甚至可以考虑使用某种数据库
回答by prasanth
Create a configuration file and put your entries there.
创建一个配置文件并将您的条目放在那里。
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
You can load this file using Properties.load(fileName)
and retrieved values you get(key)
;
您可以使用Properties.load(fileName)
和检索的值加载此文件get(key)
;
回答by Fakhredin Gholamizadeh
app.config
应用程序配置文件
app.name=Properties Sample Code
app.version=1.09
Source code:
源代码:
Properties prop = new Properties();
String fileName = "app.config";
InputStream is = null;
try {
is = new FileInputStream(fileName);
} catch (FileNotFoundException ex) {
...
}
try {
prop.load(is);
} catch (IOException ex) {
...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));
Output:
输出:
Properties Sample Code
1.09