views:

123

answers:

3

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..

+6  A: 

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

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

Or to read lines:

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

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

Jon Skeet
+9  A: 

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
I'd use the `FileUtils.readFileToString(file,encoding)` version - may as well recommend good habits!
Nick
@Nick - thanks for the suggestion
Bozho
A: 

AFAIK, there is no one-liner with standard libraries. 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 != -1) {
            c = r.read();
            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
buffered reader has a read line which would be better than reading a char at a time
Steven
If you would use a BufferedInputStream, it would not make a difference
Neeme Praks