9

I want to directly read a file, put it into a string without storing the file locally. I used to do this with an old project, but I don't have the source code anymore. I used to be able to get the source of my website this way.

However, I don't remember if I did it by "InputStream to String array of lines to String", or if I directly read it into a String.

Was there a function for this, or am I remembering wrong?

(Note: this function would be the PHP equivalent of file_get_contents($path))

3 Answers3

7

You need to use InputStreamReader to convert from a binary input stream to a Reader which is appropriate for reading text.

After that, you need to read to the end of the reader.

Personally I'd do all this with Guava, which has convenience methods for this sort of thing, e.g. CharStreams.toString(Readable).

When you create the InputStreamReader, make sure you supply the appropriate character encoding - if you don't, you'll get junk text out (just like trying to play an MP3 file as if it were a WAV, for example).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Minor: to get a Reader for a file, you can go straight to FileReader without explicitly creating an InputStream or an InputStreamReader. – Vance Maverick Feb 17 '11 at 16:06
  • 1
    @Vance: Avoid FileReader like the plague - it doesn't allow you to specify the encoding to use :( – Jon Skeet Feb 17 '11 at 16:53
3

Check out apache-commons-io and for your use case FileUtils.readFileToString(File file) (should not be to hard to get a File form the path).

You can use the library or have a look at the code - as this is open.

FrVaBe
  • 47,963
  • 16
  • 124
  • 157
1

There is no direct way to read a File into a String.

But there is a quick alternative - read the File into a Byte array and convert it into a String.

Untested:

File f = new File("/foo/bar");
InputStream fStream = new FileInputStream(f);
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
for(int data = fStream.read(); data > -1; data = fStream.read()) {
  b.write(data);
}
String theResult = new String(bStream.toByteArray(), "UTF-8");
Christian Seifert
  • 2,780
  • 5
  • 29
  • 45