gpt4 book ai didi

Java从txt文件中读取数字

转载 作者:行者123 更新时间:2023-11-30 03:03:05 26 4
gpt4 key购买 nike

假设我们有一个像这样的文本文件:

#this is a config file for John's server


MAX_CLIENT=100

# changed by Mary


TCP_PORT = 9000

我编写了以下代码:

 this.reader = new BufferedReader(new FileReader(filename));
String line;

line = reader.readLine();
while (line.length() != 0) {

line = line.trim();
if (line.contains("#") || line.contains("")) {
line = reader.readLine();

} else {
if (line.contains("MAX_CLIENT=")) {
line = line.replace("MAX_CLIENT=", "");
this.clientmax = Integer.parseInt(line);
}

if (line.contains("TCP_PORT=")) {

line = line.replace("TCP_Port=", "");
tcp_port = Integer.parseInt(line);
}

}
}

其中 clientmax 和 tcp_port 的类型为 int。

clientmax 和 tcp_port 会收到此代码的值吗?

如果我的文本文件稍微更改为:

MAX_CLIENT=100# changed by Mary

在数字后面包含评论。

ow,btw # 代表评论的开始。

谢谢。

最佳答案

您应该使用为此目的设计的类:Properties

此类为您处理评论,因此您不必担心它们。

你可以像这样使用它:

Properties prop = new Properties();
prop.load(new FileInputStream(filename));

然后您可以使用以下方法从中提取属性:

tcpPort = Integer.parseInt(prop.getProperty("tcpPort"));

或保存使用:

prop.setProperty("tcpPort", String.valueOf(tcpPort));

关于Java从txt文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35435992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com