我正在进行一个项目,构建一个线程池化的Web服务器,在这个项目中,我需要设置以下内容:
- 服务器监听的端口号。
- 线程池中有多少个线程。
- 根目录的绝对路径,以及许多其他点。
app.config
app.name=Properties Sample Code
app.version=1.09
源代码:
Properties prop = new Properties();
String fileName = "app.config";
try (FileInputStream fis = new FileInputStream(fileName)) {
prop.load(fis);
} catch (FileNotFoundException ex) {
... // FileNotFoundException catch is optional and can be collapsed
} catch (IOException ex) {
...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));
输出:
Properties Sample Code
1.09
这取决于具体情况。
首先请参考基本I/O,查看Properties,再了解Preferences API,甚至可以考虑使用Java API for XML Processing和Java Architecture for XML Binding
如果以上方法都不符合您的特定需求,您甚至可以考虑使用某种形式的数据库
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
您可以使用Properties.load(fileName)
加载此文件,并检索值,您可以使用get(key)
;
WebServer
,那么我应该把日志放在哪里? - devsdaFile f = new File(System.getProperty("user.dir")+ File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "server.properties");
对我有效。 :) :) - devsdaProperties.load
不起作用 - 它需要一个InputStream
或Reader
,而不是一个String
。https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html - andydavies