Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to convert old java I/O code to nio ...

aegir traustason
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an example code from a book called TCP/IP SOCKETS IN JAVA, by Kenneth L. Calvert and Michael J. Donahoo. It's a good book with some great examples, but the problem is that it focuses on jdk 1.3...

The following method returns a byte array representation of a class called ItemQuote.

My question is, how would it be done in java.nio? ItemQuote is just a simple bean, but what I would like to know is how to use maybe a ByteBuffer with it.

these 3 lines I would like to focus on in ItemQuoteEncoderBin.encode(ItemQuote item):

1 byte[] encodedDesc = item.itemDescription.getBytes(encoding);
2 out.writeByte(encodedDesc.length);
3 out.write(encodedDesc);

line 1) gets the byte array representation for the string
line 2) writes a byte (could be int) to tell the receiver how long the following string is going to be
line 3) writes the string

First: We don't know how long the itemDescription is going to be - that's why we have line 2

ByteBuffer allocates a fixed amount of space, when in this case we don't know how much space is needed. What if the itemDescription is bigger than the allocated space?

Does anyone have a suggestion on how to rewrite this using java.nio ?

class ItemQuoteEncoderBin:

public byte[] encode(ItemQuote item) throws Exception {

ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
byte flags = 0;
if (item.discounted)
if (item.inStock)
flags |= IN_STOCK_FLAG;
byte[] encodedDesc = item.itemDescription.getBytes(encoding);
return buf.toByteArray();

class ItemQuoteDecoderBin:

public ItemQuote decode(InputStream wire) throws IOException {
boolean discounted, inStock;
DataInputStream src = new DataInputStream(wire);
long itemNumber = src.readLong();
int quantity = src.readInt();
int unitPrice = src.readInt();
byte flags = src.readByte();
int stringLength =; // Returns an unsigned byte as an int
if (stringLength == -1)
throw new EOFException();
byte[] stringBuf = new byte[stringLength];
String itemDesc = new String(stringBuf, encoding);
return new ItemQuote(itemNumber,itemDesc, quantity, unitPrice,
((flags & IN_STOCK_FLAG) == IN_STOCK_FLAG));
Martin Mathis
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could probably get around the space limitation by using the method

ByteBuffer.wrap(byte[] array), which pretty much returns a ByteBuffer of the desired size with the desired data.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic