简体   繁体   中英

Java Read numbers from txt file

Let's assume we have a text file like this one:

#this is a config file for John's server


MAX_CLIENT=100

  # changed by Mary


TCP_PORT = 9000

And I have written the following code :

 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);
            }

        }
    }

where clientmax and tcp_port are of type int.

Will clientmax and tcp_port receive their value for this code?

What should I do if I the text file changes a little bit to:

MAX_CLIENT=100# changed by Mary

containing a comment after the number.

ow,btw # represents the start of a comment.

Thank you.

Use line.startsWith("#") instead of line.contains("#")

When you do this, keep in mind that you need to stop reading when you reach a comment character.

You should use a class designed for this purpose: Properties

This class handles comments for you so you don't have to worry about them.

You use it like this:

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

Then you can extract properties form it using:

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

Or save using:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM