0

I am wondering why with the following code:

SeekableByteChannel seeka = Files.newByteChannel(path,StandardOpenOption.CREATE,StandardOpenOption.WRITE);
    ByteBuffer src = ByteBuffer.allocate(10);
    src.putChar('a');
    src.flip();
    seeka.write(src);

I get written in the file (path) the following result: \00a. I had expected it would have been different, like only the char 'a'. If I use a CharBuffer than I cannot pass it to the seeka.write() method. I am making some experiments with these classes, I am aware that there are other ways to write a char or anything else in a file.

Thanks in advance.

Rollerball
  • 12,618
  • 23
  • 92
  • 161

1 Answers1

3

The putChar() method in the ByteBuffer class writes the Unicode for a char into the buffer. This is 16 bits or more. So when you call putChar('a'), you are putting the Unicode for 'a' into the buffer rather than the char 'a'. When you write this buffer with the SeekableByteChannel, you are writing this unicode to file, because this is what's in your buffer.

Luckily, it is a fairly simple task to convert this Unicode back into chars when reading the files. You can use the read() method in SeekableByteChannel to read the bytes into a ByteBuffer, and then call the asCharBuffer() method in ByteBuffer to treat the ByteBuffer as a CharBuffer, which will allow you to read in chars. Alternatively, you could repeatedly call the getChar() method in ByteBuffer to read in a single char. If you're looking to simply write chars to file, however, you will have to resort to a different method.

user207421
  • 305,947
  • 44
  • 307
  • 483
Alex
  • 71
  • 3
  • I see, and with FileOutputStream it write down directly the mere sheer simple byte right? without bytecodes.. that's why it works reading and writing chars from a file with FileOutputStream.. Am I right? PS I am aware that there are FileReader and FileWriter, is just to know how FileInputStream works. Thanks in advance – Rollerball Aug 11 '13 at 18:29
  • However in the API they don't mention about the bytecode: Writes two bytes containing the given char value, in the current byte order, into this buffer at the current position, and then increments the position by two. – Rollerball Aug 11 '13 at 18:33
  • @Rollerball Yes he does, and he should edit his answer accordingly if he doesn't want to attract downvotes. – user207421 Aug 11 '13 at 22:47