簡體   English   中英

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("#")

執行此操作時,請記住,到達注釋字符時需要停止閱讀。

您應該使用為此目的設計的類: 屬性

此類為您處理注釋,因此您不必擔心它們。

您可以這樣使用它:

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

然后,您可以使用以下命令從中提取屬性:

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

或使用以下方法保存:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM