【问题标题】:How to read integers from a file using BufferedReader from Java?如何使用 Java 中的 BufferedReader 从文件中读取整数?
【发布时间】:2019-03-27 01:42:20
【问题描述】:

我正在使用 Java 中的 BufferedReader,希望在读取整数方面得到一些指导。

总而言之,输入文件的每一行将代表无向图中的一条边。它将包含两个整数,即边的端点,后跟一个实数,即边的权重。最后一行将包含 -1,表示输入结束。

我已经创建了一个 BufferedReader 对象并初始化了一个整数变量和

文件格式如下:

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

这是我迄今为止所尝试的,但我想知道如何获取每一行代码,并将第一个数字作为“开始”变量,第二个数字作为“结束”变量,第三个数字是“重量”变量吗?我在网上看到了一些创建数组的解决方案,但由于我的文件格式,我有些困惑。我可以帮助澄清有关的任何细节

【问题讨论】:

  • 使用while ((line = fileReader.readLine()) != null) {,然后解析该行以提取3个数字。

标签: java file io integer bufferedreader


【解决方案1】:

我会首先检查我是否可以读取文件(您可以使用File.canRead() 来做到这一点)。接下来,我将编译一个具有三个分组操作的正则表达式。然后我会使用BufferedReader.readLine() 来读取文本行; read() 调用返回单个字符。然后它只剩下解析匹配的行。而且我认为吞下原始异常只是为了重新抛出它没有任何意义(实际上,您会丢失当前的所有堆栈跟踪信息)。综上所述,

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

【讨论】:

    【解决方案2】:

    切换到 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.");
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用readLine 而不是使用read,然后使用拆分,我认为您的分隔符是三个空格?

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 2013-09-19
        • 1970-01-01
        • 2023-03-04
        • 2013-08-02
        相关资源
        最近更新 更多