I want to read an entire file in all at once. It always be a text file no more than a few hundred bytes. The processing is very limited and it seems like overkill to have some sort of loop reading in the file...
How do I just place the entire file's contents into a String in one statement? It must be possible, yes?
file, of course, is the variable refering to a File object representing the file. fis, of course, is the FileInputStream opened using this File object.
Refer to the File and FileInputStream API doc for more info. [ June 21, 2006: Message edited by: Martin Simons ]
You could use RandomAccessFile instead of FileInputStream. There is a readFully() method there, which does guarantee to fill the array (assuming the file has enough bytes).
Use a File in place of System.in (but please note that using Scanner has a limitation that nothing following the last newline is used, so make sure your file contains a newline at the end if you intend to use this method).
The dot matches every character except possibly a newline. The (s) removes that exception. The asterisk makes it match as many such characters as there are, (zero or more characters).
Not reading the line with the EOF mark on it is probably an API bug, unless it's because of some obscure rule in the specification.
Markz Demetrez wrote:Scanner would be a great idea.
It's worth remembering that Scanner will probably (don't know about v7) be a lot slower than a BufferedReader or BufferedInputStream, because it was designed to scan text, not read files. Personally, I don't even think it does a great job of that, but I am admittedly biased.
Stu Thompson wrote:it seems like overkill to have some sort of loop reading in the file...
It's not. Not at all. Why do you think it is?
How do I just place the entire file's contents into a String in one statement? It must be possible, yes?
Why would you assume that? I mean, other than the fact that anything can be done in one statement just by putting it into a method.
And yes, I see that in Java 7, the core API now does in fact have a means to do that. However, it puts it into a byte array, which may not be what you want, given that it's a text file. And note that a) Internally that method must be looping, and b) Whatever it does is no different than something you could have written yourself and stuck into a utility method that you keep around in case you need this functionality again.