Java read file txt to string

How to read a text file as String in Java? Example

There was no easy way to read a text file as String in Java until JDK 7, which released NIO 2. This API now provides a couple of utility methods that you can use to read the entire file as String e.g. Files.readAllBytes() returns a byte array of the entire text file. You can convert that byte array to String to have a whole text file as String inside your Java program. If you need all lines of files as a List of String e.g. into an ArrayList, you can use Files.readAllLines() method. This returns a List of String, where each String represents a single line of the file.

Prior to these API changes, I used to use the BufferedReader and StringBuilder to read the entire text file as String. You iterate through the file, reading one line at a time using readLine() method and appending them into a StringBuilder until you reach the end of the file. You can still use this method if you are running on Java SE 6 or the lower version.

In this article, we’ll look at a couple of examples to demonstrate how to read a text file as a String or get a List of lines as String from a text file. I’ll also show the BufferedReader way, which you can use in Java SE 6 and earlier versions.

Читайте также:  Python telebot send image

Reading a Text File as String in Java — Files.readAllBytes() Example

This is the standard way to read the whole file as String in Java. Just make sure the file is small or medium-size and you have enough heap space to hold the text from a file into memory. If you don’t have enough memory, the below code can throw java.lang.OutOfMemoryError: Java heap space, so beware of that.

Here is the method to read a file as String in Java 7:

public static String readFileAsString(String fileName) < String text = ""; try < text = new String(Files.readAllBytes(Paths.get("file.txt"))); > catch (IOException e) < e.printStackTrace(); >return text; >

You should also be careful with character encoding. The above code assumes that the file and platform’s default character encoding are the same. If that’s not the case then use the correct character encoding while converting byte array to String in Java. See these free Java Programming online courses to learn more about character encoding and converting bytes to text in Java.

Reading Text File as String in Java — BufferedReader Example

This was the old way of reading a file as String in Java. You can see that it requires almost 8 to 10 lines of code, which can now effectively be done in just one line in Java 7. It uses the readLine() method to read the file line by line and then joined them together using StringBuilder’s append() method.

BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) < sb.append(line).append("\n"); line = br.readLine(); > String fileAsString = sb.toString();

Don’t forget to append the \n character to insert the line break, otherwise, all lines will be joined together and all text from the file will come as just one big line. If you are not familiar with \n or \r\n , I suggest you join a comprehensive Java course The Complete Java Masterclass to learn more about special characters in Java.

Java Program to read a text file as String

Here is the complete Java program to read a text file as String, it includes both JDK 6 and JDK 7 approaches to reading the content of the file in a string variable.

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /* * Java Program read a text file as String * first by using the JDK 7 utility method Files.readAllBytes() * and second by using BufferedReader and StringBuilder. */ public class ReadFileAsString < public static void main(String[] args) throws Exception < // read whole file as String in JDK 7 String data = ""; try < data = new String(Files.readAllBytes(Paths.get("file.txt"))); > catch (IOException e) < e.printStackTrace(); >System.out.println("Text file as String in Java"); System.out.println(data); // read file as String in Java SE 6 and lower version BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) < sb.append(line).append("\n"); line = br.readLine(); > String fileAsString = sb.toString(); System.out .println("whole file as String using BufferedReader and StringBuilder"); System.out.println(fileAsString); br.close(); > > Output Text file as String in Java Effective Java is the best book for senior Developers. Clean code is the best book for Junior Developers. whole file as String using BufferedReader and StringBuilder Effective Java is the best book for senior Developers. Clean code is the best book for Junior Developers.

In the second example, don’t forget to append the «\n» or «\r\n» depending upon whether you are running on Windows or UNIX, otherwise, all lines of files are concatenated into just one line. Also, don’t forget to close the BufferedReader to prevent resource leaks, especially when you are not using the automatic resource management feature of Java 7.

That’s all about how to read a text file as String in Java. You can use the new way if your program is running on JRE 7 and the old way if you are using Java 6 or lower versions. Pay attention to the character encoding of the file if you are not sure whether both file and platform’s default character encoding (the machine where your Java program is running) is not the same.

Related Java File tutorials you may like

  • How to write to a file using BufferedWriter in Java? (solution)
  • How to read/write an XLSX file in Java? (solution)
  • How to read a text file using BufferedReader in Java? (example)
  • How to load data from a CSV file in Java? (example)
  • How to append text to a file in Java? (solution)
  • How to read InputStream as Stream in Java? (example)
  • How to find the highest occurring word from a file in Java? (solution)
  • 2 ways to read a text file in Java? (solution)

That’s all about how to read data from a file as a String in Java. This is a useful technique Java developers should know, it can be helpful in many cases like loading log files or content files.

Источник

Read a File to String in Java

Learn to read a text file into String in Java. Following examples use Files.readAllBytes() , Files.lines() (to read line by line) and FileReader and BufferedReader to read a file to String.

1. Using Files.readString() – Java 11

With the new method readString() introduced in Java 11, it takes only a single line to read a file’s content into String using the UTF-8 charset .

  • In case of any error during the read operation, this method ensures that the file is properly closed.
  • It throws OutOfMemoryError if the file is extremely large, for example, larger than 2GB .
Path filePath = Path.of("c:/temp/demo.txt"); String content = Files.readString(fileName);

2. Using Files.lines() – Java 8

The lines() method reads all lines from a file into a Stream. The Stream is populated lazily when the stream is consumed.

  • Bytes from the file are decoded into characters using the specified charset.
  • The returned stream contains a reference to an open file. The file is closed by closing the stream.
  • The file contents should not be modified during the reading process, or else the result is undefined.
Path filePath = Path.of("c:/temp/demo.txt"); StringBuilder contentBuilder = new StringBuilder(); try (Stream stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) < stream.forEach(s ->contentBuilder.append(s).append("\n")); > catch (IOException e) < //handle exception >String fileContent = contentBuilder.toString();

3. Using Files.readAllBytes() – Java 7

The readAllBytes() method reads all the bytes from a file into a byte[]. Do not use this method for reading large files.

This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all the bytes, we pass those bytes to String class constructor to create a new String.

Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; try < byte[] bytes = Files.readAllBytes(Paths.get(filePath)); fileContent = new String (bytes); >catch (IOException e) < //handle exception >

4. Using BufferedReader – Java 6

If you are still not using Java 7 or later, then use BufferedReader class. Its readLine() method reads the file one line at a time and returns the content .

Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; StringBuilder contentBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) < String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) < contentBuilder.append(sCurrentLine).append("\n"); >> catch (IOException e) < e.printStackTrace(); >fileContent = contentBuilder.toString();

We can use the utility classes provided by the Apache Commons IO library. The FileUtils.readFileToString() is an excellent way to read a whole file into a String in a single statement.

File file = new File("c:/temp/demo.txt"); String content = FileUtils.readFileToString(file, "UTF-8");

Guava also provides Files class that can be used to read the file content in a single statement.

File file = new File("c:/temp/demo.txt"); String content = com.google.common.io.Files.asCharSource(file, Charsets.UTF_8).read();

Use any of the above-given methods for reading a file into a string using Java.

Источник

Оцените статью