file readlines java 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: java read each lines in file
BufferedReader br = null;
try {
File file = new File("myfile.txt"); // java.io.File
FileReader fr = new FileReader(file); // java.io.FileReader
br = new BufferedReader(fr); // java.io.BufferedReader
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
catch(IOException e) { e.printStackTrace();}
finally
{
try { if (br != null) br.close(); }
catch(IOException e) { e.printStackTrace(); }
}