java file readline code example
Example 1: java read file text
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}
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();
}