Java BufferedReader read String line by line and convert to integer

Description

Java BufferedReader read String line by line and convert to integer


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String fileName = "input.txt";
    try (BufferedReader fileReader = new BufferedReader(new FileReader(fileName));) {
      long sum = 0;
      while (true) {
        String lineRead = fileReader.readLine();
        if (lineRead == null) {
          // End of file is reached
          break;// www .  j  a  v  a2 s . c  om
        }
        long num = Integer.parseInt(lineRead);
        sum += num;
      }
      System.out.println(sum);
    }catch (IOException ioex) {
      System.err.println("Error");
    }
  }
}



PreviousNext

Related