• 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 ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

NIO problem.

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Wanderer
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic