how to scan the lines in a file injava code example

Example 1: reading in lines from a file java

private ArrayList<String> readFileLines(String filepath) throws FileNotFoundException, IOException{
  File fp = new File(filepath);
  FileReader fr = new FileReader(fp);
  BufferedReader br = new BufferedReader(fr);

  ArrayList<String> lines = new ArrayList<>();
  String line;
  while((line = br.readLine()) != null) { lines.add(line); }

  fr.close();
  return lines;
}

Example 2: how to check the lines in a file java scanner

int count = 0;
while (scanner.hasNextLine()) {
    count++;
    scanner.nextLine();
}

Tags:

Java Example