Re: java.io.File to java.lang.String
Tom Hawtin wrote:
FileReader fileReader = new FileReader(file);
CharBuffer charBuffer = CharBuffer.allocate((int)file.length());
This could allocate a buffer three times to large,
Jeff Higgins wrote:
Going over Javadocs... could you elaborate?
Because Strings and Chars are encoded, as are files. UTF-8, for example, uses
one to three bytes per character depending on the character set and other
factors.
I'm not sure about how Tom arrived at three times as large but I can easily
see how the CharBuffer could be twice as large as the file data. CharBuffers
are allocated at two bytes per character. A file encoding that uses 8 bits
per character will only fill half such a buffer. I'm guessing that Tom is
familiar with some combination of encoding schemes that would have the
CharBuffer wind up three times too large for the file.
or way too small for a huge file.
If the file uses a multibyte encoding with lots of characters that require
more than two bytes each.
fileReader.read(charBuffer);
This does not necessarily read all that could be read. Should be in a
loop.
Again, I'm sorry but I haven't been able to figure out what might
cause read(charBuffer) to not read all that could be read?
Is this a sufficent loop?
while(fileReader.ready()){fileReader.read(charBuffer);}
No. You'll have to fill the buffer, flip() it, read it to store or processe
the data, then rewind() and repeat. I haven't played with java.nio much but
if I erred here someone should step up and correct me pretty quickly.
<http://java.sun.com/developer/technicalArticles/releases/nio/index.html>
<http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html>
GIYF.
--
Lew