简体   繁体   English

如何使用Java的BufferedReader从文件读取整数?

[英]How to read integers from a file using BufferedReader from Java?

I am working with BufferedReader in Java and was hoping for some guidance when it comes to reading integers. 我正在使用Java中的BufferedReader进行操作,希望在读取整数时获得一些指导。

To summarize, each line of the input file will represent one edge in an undirected graph. 总而言之,输入文件的每一行将代表无向图中的一条边。 It will contain two integers, the endpoints of the edge, followed by a real number, the weight of the edge. 它包含两个整数,即边缘的端点,后跟一个实数,即边缘的权重。 The last line will contain a -1, to denote the end of input. 最后一行将包含-1,以表示输入的结尾。

I have created a BufferedReader object and initialized an integer variable and 我创建了一个BufferedReader对象并初始化了一个整数变量,然后

The format of the file is as follows: 该文件的格式如下:

 0   1    5.0
 1   2    5.0
 2   3    5.0
...
 5  10    6.0
 5  11    4.0
17  11    4.0
-1
public static void processFile(String inputFilePath) throws IOException {
        //Check to see if file input is valid
        if (inputFilePath == null || inputFilePath.trim().length() == 0) {
            throw new IllegalArgumentException("Error reading file.");
        }

        //Initialize required variables for processing the file
        int num = 0;
        int count = 0;

        try {
            //We are reading from the file, so we can use FileReader and InputStreamReader.
            BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath));
            //Read numbers from the line
            while ((num = fileReader.read()) != -1) { //Stop reading file when -1 is reached
                //First input is the start

                //Second input is the end
                //Third input is the weight



            }
        } catch (IOException e) {
            throw new IOException("Error processing the file.");
        }
    } 

This is what I have attempted thus far, but I wondering how I can take each line of code, and have the first number be the "start" variable, the second number be the "end" variable, and the third number be the "weight" variable? 到目前为止,这是我尝试过的方法,但是我想知道如何使用每一行代码,并让第一个数字为“开始”变量,第二个数字为“结束”变量,第三个数字为“重量”变量? I saw some solutions online to create an array but because of the format of my file I am somewhat confused. 我在网上看到一些创建数组的解决方案,但是由于文件格式的原因,我有些困惑。 I can help clarify any details about 我可以帮助澄清有关

Switch up to readLine and use a Scanner: 切换到readLine并使用扫描仪:

public static void processFile(String inputFilePath) throws IOException {
    // Check to see if file input is valid
    if (inputFilePath == null || inputFilePath.trim()
                                              .length() == 0) {
        throw new IllegalArgumentException("Error reading file.");
    }

    // Initialize required variables for processing the file
    String line;
    int count = 0;

    // We are reading from the file, so we can use FileReader and InputStreamReader.
    try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) {

        // Read numbers from the line
        while ((line = fileReader.readLine()) != null) { // Stop reading file when -1 is reached
            Scanner scanner = new Scanner(line);

            // First input is the start
            int start = scanner.nextInt();

            if (start == -1) {
                break;
            }

            // Second input is the end
            int end = scanner.nextInt();

            // Third input is the weight
            double weight = scanner.nextDouble();

            // do stuff
        }
    } catch (IOException e) {
        throw new IOException("Error processing the file.");
    }
}

I would start by checking that I can read the file (you can use File.canRead() to do that). 我将首先检查我是否可以读取文件(可以使用File.canRead()来做到这一点)。 Next, I would compile a regular expression with three grouping operations. 接下来,我将使用三个分组操作来编译一个正则表达式 Then I would use BufferedReader.readLine() to read lines of text; 然后,我将使用BufferedReader.readLine()读取文本行; the read() call returns a single character. read()调用返回单个字符。 Then it only remains to parse matching lines. 然后只剩下解析匹配的行。 And I see no purpose in swallowing the original exception only to rethrow it (in fact, you lose all stack trace information your current way). 而且我认为吞下原始异常只是为了重新抛出异常没有任何目的(实际上,您丢失了当前方式的所有堆栈跟踪信息)。 Putting that all together, 放在一起

public static void processFile(String inputFilePath) throws IOException {
    File f = new File(inputFilePath);
    if (!f.canRead()) {
        throw new IllegalArgumentException("Error reading file.");
    }

    // Initialize required variables for processing the file
    try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) {
        Pattern p = Pattern.compile("^\\s*(\\d+)\\s+(\\d+)\\s+(\\d.+)$");
        String line;
        while ((line = fileReader.readLine()) != null) {
            Matcher m = p.matcher(line);
            if (m.matches()) {
                int start = Integer.parseInt(m.group(1));
                int end = Integer.parseInt(m.group(2));
                double weight = Double.parseDouble(m.group(3));
                System.out.printf("start=%d, end=%d, weight=%.2f%n", start, end, weight);
            }
        }
    }
}

Instead of using read you can just use readLine then use split with your separator being three spaces I think? 除了使用read您还可以使用readLine然后使用split并将分隔符readLine三个空格,我认为呢?

        try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) {
            String line;
            while(!(line = fileReader.readLine()).equals("-1")) {
                String[] edge = line.split("   ");
                int start = Integer.parseInt(edge[0]);
                int end = Integer.parseInt(edge[1]);
                double weight = Double.parseDouble(edge[2]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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