Reading a text file
Posted on 2005-04-21
I'm using some code based on some from a book to try to read a text file and print it out, but it doesn't seem to work.
I've simplified it as much as I can, including removing the exception handling etc.
When I step through it in the debugger, it seems to go wrong when it converts the Charbuffer to a string. The buffer in ByteBuffer looks OK to me. But when it converts it to a String, instead of there being 10 ascii characters, there are just 5 characters that look to me like Chinese.
My question is this... what's wrong with the code, please?
public class TestFileIO
private static final String TEST_FILENAME = "C:/tmp/test.txt";
private static final int INPUT_BUFFER_SIZE = 10;
/** Creates a new instance of TestFileIO */
public TestFileIO ()
public static void main (String args) throws Exception
File file = new File ( TEST_FILENAME );
FileInputStream inputFile = null;
inputFile = new FileInputStream ( file );
FileChannel inChannel = inputFile.getChannel();
ByteBuffer buff = ByteBuffer.allocate ( INPUT_BUFFER_SIZE );
while ( inChannel.read ( buff ) != -1 ) // read next chunk from file
CharBuffer charBuffer = buff.asCharBuffer ();
String str = charBuffer.toString ();
System.out.println ( str );
System.out.println ( "EOF reached" );