Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

NIO problem.  RSS feed

 
Stef Mischook
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Just playing with NIO for the first time and I am reading from text files from a collection of file objects and the reads always result in:

???

Where as if I read the same files with the old Java IO I get the actual text.

My code:

FileInputStream inFile = null;
try {
inFile = new FileInputStream(files[i]);
}
catch(FileNotFoundException e) {
System.out.println("Eror reading file"+e);
}

FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
while(inChannel.read(buf) != -1) {
System.out.println("String read: "+ ((ByteBuffer)(buf.flip())).asCharBuffer().toString());
buf.clear();
}

}
catch(IOException e) {

}


Any ideas what I'm doing wrong here? I think it has to do with my byte buffer casting?:

((ByteBuffer)(buf.flip())).asCharBuffer().toString());

Thanks,

Stef
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
asCharBuffer() is not what you want here - unless the character encoding happens to be UTF-16, maybe. You need to know what character encoding the files uses, and use that encoding to translate from bytes to chars. Something like this:

I assumed UTF-8 for encoding; replace as apprpriate. If you're not sure what the encoding is, just try some common ones: UTF-8, ISO-8859-1, Cp-1252, UTF-16. (You won't notice a difference between the first three unless you use some non-US-ASCII chars like é or ™ - those sorts of things are represented differently in different systems.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!