131

Possible Duplicate:
How to create a Java String from the contents of a file
Whole text file to a String in Java

I am trying to read the contents of a file using FileReader . But i want to read the file without reading a line by line . Is it possible to read the whole file without loop. I am using the following code

 try
 {
     File ff=new File("abc.txt");
     FileReader fr=new FileReader(ff);

     String s;
     while(br.read()!=-1)
     {
          s=br.readLine();
     }
 }

 catch(Exception ex)
 {
     ex.printStackTrace();
 }
2
  • This code won't compile to begin with. Commented Oct 23, 2018 at 14:49
  • 2
    There is a one-line Java 11 solution to this: stackoverflow.com/a/52301018/942774 Commented Feb 26, 2019 at 7:27

5 Answers 5

214

Java 7 one line solution

List<String> lines = Files.readAllLines(Paths.get("file"), StandardCharsets.UTF_8);

or

 String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);
Sign up to request clarification or add additional context in comments.

7 Comments

Can't find that Files in Android.
Not all Java answers have to be suited to Android, @akauppi! Just look for a solution that Android supports from another answer!
String text = Files.readString(Paths.get("file")); is even shorter, assuming that you want a UTF-8 String output.
And if you already have the File object, you can do file.toPath() inside readAllBytes
Important for Android: Call requires API level 26: java.nio.file.Files#readAllBytes - same thing for readString.
|
144

If the file is small, you can read the whole data once:

File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();

String str = new String(data, "UTF-8");

6 Comments

Does not work for InputStream's s.a. Android assets (no length)
How small is "small"?
@silver Entire content of the file will be stored in memory. So, avoid reading 5GB files like this :-)
Note: file.length() may return 0 for files under /proc. And in those cases this snippet will return an empty string.
Also read might not fill the entire buffer. It might work in practice with most JREs, but there's no guarantee in the API.
|
36

You can try using Scanner if you are using JDK5 or higher.

Scanner scan = new Scanner(file);  
scan.useDelimiter("\\Z");  
String content = scan.next(); 

Or you can also use Guava

String data = Files.toString(new File("path.txt"), Charsets.UTF8);

4 Comments

Note that the scanner should be closed after use.
String data = Files.toString(new File("path.txt"), Charsets.UTF_8);. Just a small typo. :-)
This code with Scanner only read first 1024 bytes from file. Look at source code. It read buffer and check it with this regexp. This always valid - then it return all buffer content. By default buffer have size of 1024 bytes.
This is BAD approach. The correct solution (for Java 1.7 and higher) is Files.readAllLines(). For legacy JREs, FileInputStream.read() is probably best. I'm not sure if it's portable to all platforms (i.e. Ctl-Z is recognized everywhere), and it 's easy to miss doing a Scanner.close().
36

If you are using Java 5/6, you can use Apache Commons IO for read file to string. The class org.apache.commons.io.FileUtils contais several method for read files.

e.g. using the method FileUtils#readFileToString:

File file = new File("abc.txt");
String content = FileUtils.readFileToString(file);

3 Comments

This is probably the easiest solution using a 3rd-party lib.
Minimal code to write; Many more libraries to add to project.
The method readFileToString(File) from the type FileUtils is deprecated
22

Since Java 11 you can do it even simpler:

import java.nio.file.Files;

Files.readString(Path path);
Files.readString​(Path path, Charset cs)

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

2 Comments

Only if the file is smaller than 1GB. :-)
Good point, but it looks like it's 2GB instead of 1GB

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.