How to read a textfile and output it , BufferedReader & Scanner
910 views Here's a demo I wrote some time ago to read a file and output it in the console. I've created 2 versions. One that uses the "Scanner object" and the other the "BufferedReader object" to read the text files from disk.
Both examples of mine work, but the Scanner version is preferred.
BufferedReader version:
JAVA:
-
public class ReadFile {
-
ReadFile rf = new ReadFile();
-
rf.readFile();
-
}
-
public void readFile(){
-
try {
-
String tmp;
-
tmp = br.readLine(); // read first line of file.
-
while(tmp != null){ // read a line until end of file.
-
tmp = br.readLine();
-
}
-
br.close();
-
e.printStackTrace();
-
e.printStackTrace();
-
}
-
}
-
}
Scanner version:
JAVA:
-
public class ReadLineDemo {
-
ReadLineDemo EDS = new ReadLineDemo();
-
EDS.readFile();
-
}
-
public void readFile(){
-
String str;
-
FileReader fr;
-
try {
-
Scanner sc = new Scanner(fr);
-
while(sc.hasNext()){
-
str = sc.nextLine();
-
}
-
}
-
e.printStackTrace();
-
}
-
}
-
}

(2 votes, average: 4.5 out of 5)


