Win a copy of Head First Android this week in the Android forum!
  • 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 ...
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • Al Hobbs
  • salvin francis

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( != -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.
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic