read all lines in a file java code example
Example 1: java read each lines in file
BufferedReader br = null;
try {
File file = new File("myfile.txt");
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
}
}
catch(IOException e) { e.printStackTrace();}
finally
{
try { if (br != null) br.close(); }
catch(IOException e) { e.printStackTrace(); }
}
Example 2: java read lines from file
Scanner sc = null;
try {
File file = new File("myfile.txt");
sc = new Scanner(file);
String line;
while (sc.hasNextLine()) {
line = sc.nextLine();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
finally {
if (sc != null) sc.close();
}