Read all text from a file into a String in Java
This post will discuss how to read all text from a file into a string in Java.
There are several ways to read the contents of a file into a string using Plain Java and third-party libraries such as Guava, Apache Commons IO, etc. Also, with the introduction of the Files class in Java 7, several static methods are included with each subsequent release that operate on files, directories, or other types of files. All these are discussed below in detail:
1. Using Java 7 (java.nio.file.Files.readAllBytes)
To read all the bytes from a file, we can use the readAllBytes() method, which takes the path to the file and returns a byte array containing the bytes read from the file. To get output in the string format, pass the byte array to the String constructor with a charset for decoding.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; class Main { public static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
2. Using Java 7 (java.nio.file.Files.readAllLines)
To read the contents of a file into a string, we can use the readAllLines() method, which takes the file’s path. It is overloaded to additionally accept the charset to be used for decoding.
This method is convenient to read all lines in a single operation but returns a list of strings and strips line terminators from the end of each line. We can easily handle this by joining each of the elements of the list with a line separator, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; class Main { public static String readFile(String path, Charset encoding) throws IOException { List<String> lines = Files.readAllLines(Paths.get(path), encoding); return String.join(System.lineSeparator(), lines); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
3. Using Java 8 (java.nio.file.Files.lines)
Java 8 introduced Files.lines() method, which can read all lines from a file as a stream. It takes the path to the file and overloaded it to accept the charset for decoding.
Like Files.readAllLines(), Files.lines() method doesn’t include line-termination characters, which can be handled explicitly, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; class Main { public static String readFile(String path, Charset encoding) throws IOException { String content = Files.lines(Paths.get(path), encoding) .collect(Collectors.joining(System.lineSeparator())); return content; } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
4. Using Java 8 (java.io.BufferedReader.lines)
Java 8 also introduced BufferedReader.lines() method, which returns a stream of lines of text read from BufferedReader. This is demonstrated below using Stream:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.stream.Collectors; class Main { public static String readFile(String path) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(path))); return reader.lines().collect(Collectors.joining(System.lineSeparator())); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
5. Using Java 11 (java.nio.file.Files.readString)
Java 11 introduced the Files.readString() method, which can read all characters from a file into a string. It takes a path to the file and overloaded to accept the charset used for decoding from bytes to characters.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; class Main { public static String readFile(String path, Charset encoding) throws IOException { return Files.readString(Paths.get(path), encoding); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
6. Using Guava’s Files.asCharSource()
Several third-party libraries provide utility methods for working with files. Guava provides the Files.asCharSource() method, which can be used to read file contents into a string using the given character set, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import com.google.common.base.Charsets; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; class Main { public static String readFile(String path, Charset encoding) throws IOException { return Files.asCharSource(new File(path), encoding).read(); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
7. Using Guava’s Files.readLines()
If you prefer Google’s Guava library, you can use the Files.readLines(file, charset) method reads all the lines from a file and returns a mutable List. For an ImmutableList, use Files.asCharSource(file, charset).readLines(). Note that both these methods strip line-termination characters from the end of each line.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; class Main { public static String readFile(String path, Charset encoding) throws IOException { List<String> lines = Files.readLines(new File(path), encoding); return Joiner.on(System.lineSeparator()).join(lines); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
8. Using Apache Commons IO
Like Guava library, Apache Commons IO FileUtils class provides the readFileToString() method that allows you to read the contents of any file into a string using the specified charset for converting Bytes from the file into characters.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; class Main { public static String readFile(String path, Charset encoding) throws IOException { return FileUtils.readFileToString(new File(path), encoding); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
Alternatively, we can use IOUtils class from Apache Commons IO library that has the toString() method. It takes an InputStream and renders its contents as a String, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { File file = new File("demo.txt"); String fileContents; try (FileInputStream inputStream = new FileInputStream(file)) { fileContents = IOUtils.toString(inputStream, StandardCharsets.UTF_8); System.out.println(fileContents); } catch (IOException e) { e.printStackTrace(); } } } |
9. Using Scanner
We can also construct a Scanner that produces values scanned from the specified file. This is demonstrated below using the try-with-resources block to automatically takes care of scanner.close().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Scanner; class Main { public static String readFile(String path, Charset encoding) throws IOException { String content; try (Scanner scanner = new Scanner(new File(path), String.valueOf(encoding))) { content = scanner.useDelimiter("\\A").next(); } return content; } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
10. Plain Java
In plain Java, we can open an input stream of bytes using InputStream and keep reading bytes of data from it into a byte array using its read() method. Finally, to get output in the string format, pass the byte array to the String constructor with a charset for decoding.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; class Main { public static String readFile(String path, Charset encoding) throws IOException { File file = new File(path); InputStream in = new FileInputStream(file); byte[] bytes = new byte[(int)file.length()]; int offset = 0; while (offset < bytes.length) { int result = in.read(bytes, offset, bytes.length - offset); if (result == -1) { break; } offset += result; } return new String(bytes, encoding); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
Another solution in plain Java is to use the BufferedReader with InputStreamReader. Each invocation of the readLine() method would read bytes from the file, convert them into characters, and then return. The following solution uses a StringBuilder to form a string from file contents using a platform-dependent line separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.io.*; class Main { public static String readFile(String path) throws IOException { StringBuilder sb = new StringBuilder(); FileInputStream fileStream = new FileInputStream(new File(path)); BufferedReader br = new BufferedReader(new InputStreamReader(fileStream)); String line; while ((line = br.readLine()) != null) { sb.append(line + System.lineSeparator()); } return sb.toString(); } public static void main(String[] args) { String filePath = "doc.txt"; String content = null; try { content = readFile(filePath); } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
Another solution in plain Java is to use a FileReader to read the whole file into a character array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.File; import java.io.FileReader; import java.io.IOException; class Main { public static void main(String[] args) { File file = new File("demo.txt"); try(FileReader fr = new FileReader(file)) { char[] chars = new char[(int) file.length()]; fr.read(chars); String fileContent = new String(chars); System.out.println(fileContent); } catch (IOException e) { e.printStackTrace(); } } } |
That’s all about copying text from a file into a Java String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)