Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text
Príliš žlutoucký kun
úpel dábelské ódy
and the file uses windows-1250 format. If you use FileReader you will get this result:
P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy
So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.
Example:
String encoding = "Cp1250";
File file = new File("foo.txt");
if (file.exists()) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
System.out.println("file doesn't exist");
}
In case you want to read the file character after character do not use BufferedReader.
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
int data = isr.read();
while (data != -1) {
System.out.print((char) data);
data = isr.read();
}
} catch (IOException e) {
e.printStackTrace();
}
For those new to Java and wondering why Jiri's answer doesn't work, make sure you do what he says and handle the exception or else it won't compile. Here's the bare minimum:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
for (String line; (line = br.readLine()) != null;) {
System.out.print(line);
}
br.close()
}
}
With Java 7's try-with-resources Jiri's answer can be improved upon:
try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
Add exception handling at the place of your choice, either in this try
or elsewhere.
Why hasn't anyone thought it was worth mentioning Scanner?
Scanner input = new Scanner(new File("foo.txt"));
while (input.hasNextLine())
{
System.out.println(input.nextLine());
}
Source: Stackoverflow.com