【发布时间】:2012-10-03 05:22:13
【问题描述】:
我正在尝试用 Java 编写一个配置文件,并将我的端口号放入其中以便我的 HTTP Web 服务器连接到根路径。
配置文件:
root= some root
port=8020
我正在尝试访问这样的属性:
FileInputStream file = new FileInputStream("config.txt");
//loading properties from properties file
config.load(file);
int port = Integer.parseInt(config.getProperty("port"));
System.out.println("this is port " + port);
如果我在 getProperty 方法中使用单个参数执行此操作,我会收到此错误
"java.lang.NumberFormatException: null"
但是,如果我这样访问它
int port = Integer.parseInt(config.getProperty("port", "80"));
它有效。
另外,它适用于config.getProperty("root");,所以我不明白...
编辑:
import java.net.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class Server
{
public static void main(String[] args) throws Exception
{
boolean listening = true;
ServerSocket server = null;
Properties config = new Properties();
int port = 0;
try
{
//Reading properties file
FileInputStream file = new FileInputStream("config.txt");
//loading properties from properties file
config.load(file);
port = Integer.parseInt(config.getProperty("port"));
System.out.println("this is port " + port);
System.out.println("Server binding to port " + port);
server = new ServerSocket(port);
}
catch(FileNotFoundException e)
{
System.out.println("File not found: " + e);
}
catch(Exception e)
{
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Server successfully binded to port " + port);
while(listening)
{
System.out.println("Attempting to connect to client");
Socket client = server.accept();
System.out.println("Successfully connected to client");
new HTTPThread(client, config).start();
}
server.close();
}
}
【问题讨论】:
-
你能提供一个独立的例子来重现你的问题吗?我怀疑当你重新检查你的测试时,你会发现
port没有被加载。 -
OP,我们正在尝试帮助格式化代码(属性)。为什么要还原版本?顺便说一句this 可能会有所帮助。
-
似乎config.txt中的“端口”属性不存在。
-
哦,抱歉,我没注意到。我注意到了一些错误,所以我对其进行了编辑。
-
@JohnathanAu 把完整的代码放在这里,展示正确读取根目录和错误读取一次加载后的端口。
标签: java file-io properties