Java 从 txt 文件中读取数字

Java Read numbers from txt file

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

#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 # 表示评论的开始。

谢谢。

使用line.startsWith("#")代替line.contains("#")

执行此操作时,请记住,当您到达评论字符时需要停止阅读。

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

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

你这样使用它:

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

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

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

或使用以下方式保存:

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