60

Does Java has a one line instruction to read to a text file, like what C# has?

I mean, is there something equivalent to this in Java?:

String data = System.IO.File.ReadAllText("path to file");

If not... what is the 'optimal way' to do this...?

Edit:
I prefer a way within Java standard libraries... I can not use 3rd party libraries..

dimo414
  • 47,227
  • 18
  • 148
  • 244
Betamoo
  • 14,964
  • 25
  • 75
  • 109
  • Possible duplicate of [How do I create a Java string from the contents of a file?](https://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file) – Vadzim May 09 '19 at 11:21

10 Answers10

50

apache commons-io has:

String str = FileUtils.readFileToString(file, "utf-8");

But there is no such utility in the standard java classes. If you (for some reason) don't want external libraries, you'd have to reimplement it. Here are some examples, and alternatively, you can see how it is implemented by commons-io or Guava.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 5
    I'd use the `FileUtils.readFileToString(file,encoding)` version - may as well recommend good habits! – Nick Oct 03 '10 at 12:33
28

Not within the main Java libraries, but you can use Guava:

String data = Files.asCharSource(new File("path.txt"), Charsets.UTF_8).read();

Or to read lines:

List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );

Of course I'm sure there are other 3rd party libraries which would make it similarly easy - I'm just most familiar with Guava.

dimo414
  • 47,227
  • 18
  • 148
  • 244
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
28

Java 11 adds support for this use-case with Files.readString, sample code:

Files.readString(Path.of("/your/directory/path/file.txt"));

Before Java 11, typical approach with standard libraries would be something like this:

public static String readStream(InputStream is) {
    StringBuilder sb = new StringBuilder(512);
    try {
        Reader r = new InputStreamReader(is, "UTF-8");
        int c = 0;
        while ((c = r.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}

Notes:

  • in order to read text from file, use FileInputStream
  • if performance is important and you are reading large files, it would be advisable to wrap the stream in BufferedInputStream
  • the stream should be closed by the caller
Neeme Praks
  • 8,956
  • 5
  • 47
  • 47
24

Java 7 improves on this sorry state of affairs with the Files class (not to be confused with Guava's class of the same name), you can get all lines from a file - without external libraries - with:

List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);

Or into one String:

String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));

If you need something out of the box with a clean JDK this works great. That said, why are you writing Java without Guava?

dimo414
  • 47,227
  • 18
  • 148
  • 244
  • The path in the second example is of type Path and can be retrieved from a String with var path = Paths.get(filePathAsString); – Stefan Mar 07 '19 at 07:27
  • All of `Files` methods use `Path`; see the [`java.nio.file` package](https://docs.oracle.com/javase/8/docs/api/java/nio/file/package-summary.html). `Paths.get()` is just one way to get a `Path` instance. – dimo414 Mar 12 '19 at 08:31
11

In Java 8 (no external libraries) you could use streams. This code reads a file and puts all lines separated by ', ' into a String.

try (Stream<String> lines = Files.lines(myPath)) {
    list = lines.collect(Collectors.joining(", "));
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}
Kris
  • 4,595
  • 7
  • 32
  • 50
5

With JDK/11, you can read a complete file at a Path as a string using Files.readString(Path path):

try {
    String fileContent = Files.readString(Path.of("/foo/bar/gus"));
} catch (IOException e) {
    // handle exception in i/o
}

the method documentation from the JDK reads as follows:

/**
 * Reads all content from a file into a string, decoding from bytes to characters
 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
 * The method ensures that the file is closed when all content have been read
 * or an I/O error, or other runtime exception, is thrown.
 *
 * <p> This method is equivalent to:
 * {@code readString(path, StandardCharsets.UTF_8) }
 *
 * @param   path the path to the file
 *
 * @return  a String containing the content read from the file
 *
 * @throws  IOException
 *          if an I/O error occurs reading from the file or a malformed or
 *          unmappable byte sequence is read
 * @throws  OutOfMemoryError
 *          if the file is extremely large, for example larger than {@code 2GB}
 * @throws  SecurityException
 *          In the case of the default provider, and a security manager is
 *          installed, the {@link SecurityManager#checkRead(String) checkRead}
 *          method is invoked to check read access to the file.
 *
 * @since 11
 */
public static String readString(Path path) throws IOException 
Naman
  • 27,789
  • 26
  • 218
  • 353
  • And it was about frickin' time you could do this. I don't see the point in reading lines and throwing away the line end encoding. – Maarten Bodewes Sep 22 '18 at 22:55
3

No external libraries needed. The content of the file will be buffered before converting to string.

Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
SzB
  • 1,027
  • 10
  • 12
  • 2
    Note [`String(byte[], String)`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String%28byte[],%20java.lang.String%29) throws an `UnsupportedEncodingException`. You should prefer the [`String(byte[], Charset)`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String%28byte[],%20java.nio.charset.Charset%29) constructor along with the constants in [`StandardCharsets`](http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html) or Guava's [`Charsets`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Charsets.html). – dimo414 Jul 20 '14 at 16:14
  • This is a code only answer, and your answer fails to mention that it requires the buffering of all bytes before converting it to a string (i.e. it is not very memory efficient). – Maarten Bodewes Sep 22 '18 at 23:06
0

No external libraries needed. The content of the file will be buffered before converting to string.

  String fileContent="";
  try {
          File f = new File("path2file");
          byte[] bf = new byte[(int)f.length()];
          new FileInputStream(f).read(bf);
          fileContent = new String(bf, "UTF-8");
      } catch (FileNotFoundException e) {
          // handle file not found exception
      } catch (IOException e) {
          // handle IO-exception
      }
Community
  • 1
  • 1
SzB
  • 1,027
  • 10
  • 12
  • But only if you never followed the I/O stream tutorials and don't understand how to handle errors and if you want to copy all characters into a buffer before converting them to a string. Please describe your answers, code only answers are generally not upvoted. – Maarten Bodewes Sep 22 '18 at 23:07
  • It's lacking a close statement for the stream, but besides that, this suggestion's general principle is useful for smaller files. – Nyerguds Jun 22 '21 at 15:58
0

Here are 3 ways to read a text file in one line, without requiring a loop. I documented 15 ways to read from a file in Java and these are from that article.

Note that you still have to loop through the list that's returned, even though the actual call to read the contents of the file requires just 1 line, without looping.

1) java.nio.file.Files.readAllLines() - Default Encoding

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    List  fileLinesList = Files.readAllLines(file.toPath());

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}

2) java.nio.file.Files.readAllLines() - Explicit Encoding

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines_Encoding {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    //use UTF-8 encoding
    List  fileLinesList = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}

3) java.nio.file.Files.readAllBytes()

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}
gomisha
  • 2,587
  • 3
  • 25
  • 33
0

Not quite a one liner and probably obsolete if using JDK 11 as posted by nullpointer. Still usefull if you have a non file input stream

InputStream inStream = context.getAssets().open(filename);
Scanner s = new Scanner(inStream).useDelimiter("\\A");
String string = s.hasNext() ? s.next() : "";
inStream.close();
return string;
mir
  • 371
  • 2
  • 5