Reading a plain text file in Java
My favorite way to read a small file is to use a BufferedReader and a StringBuilder. It is very simple and to the point (though not particularly effective, but good enough for most cases):
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
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();
} finally {
br.close();
}
Some has pointed out that after Java 7 you should use try-with-resources (i.e. auto close) features:
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();
}
When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation.
Though if I want to actually just read a file into a String, I always use Apache Commons IO with the class IOUtils.toString() method. You can have a look at the source here:
http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html
FileInputStream inputStream = new FileInputStream("foo.txt");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
And even simpler with Java 7:
try(FileInputStream inputStream = new FileInputStream("foo.txt")) {
String everything = IOUtils.toString(inputStream);
// do something with everything string
}
ASCII is a TEXT file so you would use Readers
for reading. Java also supports reading from a binary file using InputStreams
. If the files being read are huge then you would want to use a BufferedReader
on top of a FileReader
to improve read performance.
Go through this article on how to use a Reader
I'd also recommend you download and read this wonderful (yet free) book called Thinking In Java
In Java 7:
new String(Files.readAllBytes(...))
(docs) or
Files.readAllLines(...)
(docs)
In Java 8:
Files.lines(..).forEach(...)
(docs)
The easiest way is to use the Scanner
class in Java and the FileReader object. Simple example:
Scanner in = new Scanner(new FileReader("filename.txt"));
Scanner
has several methods for reading in strings, numbers, etc... You can look for more information on this on the Java documentation page.
For example reading the whole content into a String
:
StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
sb.append(in.next());
}
in.close();
outString = sb.toString();
Also if you need a specific encoding you can use this instead of FileReader
:
new InputStreamReader(new FileInputStream(fileUtf8), StandardCharsets.UTF_8)
Here is a simple solution:
String content = new String(Files.readAllBytes(Paths.get("sample.txt")));
Or to read as list:
List<String> content = Files.readAllLines(Paths.get("sample.txt"))