• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

NIO problem.

Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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());

catch(IOException e) {


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



Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic