Forums Register Login

How can I use a FileChannel and a ByteBuffer to read a UTF string

+Pie Number of slices to send: Send
Hi,
Does anyone out there have any idea how I can read UTF strings using java.nio.*?
I working on the developer certification and I want to convert from using pre jdk1.4 to using java.nio. Part of the database file has the following format; a UTF string followed by an int that has the length of the string.
So the pattern of data in the file would be. UTF string, int, UTF string int, �
Now the original project was reading the data something like this.

String[] strings = new String[numStrings];
int lengths = new int[numStrings];
File f = new File(fName);
if (f.exists() && f.canRead() && f.canWrite()) {
db = new RandomAccessFile(f, "rw");

for (int i=0; i <numStrings; i++) {
strings[i] = db.readUTF()
lengths[i] = db.readInt());
}
}
It works fine but I would like to take advantage of java.nio. Here is the best I could come up with.
String[] strings = new String[numStrings];
Int lengths = new int[numStrings];
if (f.exists() && f.canRead() && f.canWrite()) {

db = new RandomAccessFile(f, "rw");
fcDb = db.getChannel();
ByteBuffer buff = ByteBuffer.allocate(maxStringLen);
// wrap ByteBuffer so UTF strings can be read.
ByteArrayInputStream bais = new ByteArrayInputStream(buff.array());
DataInputStream dis = new DataInputStream(bais);


for (int i=0; i <numStrings; i++) {
strings[i] = dis.readUTF()
lengths[i] = dis.readInt());
}
}
It works but is it ever ugly.
Any suggestions on a better way to read a UTF string using buffers and fileChannels?
Many thanks in advance.
+Pie Number of slices to send: Send
Why do you want to change it? It will not get you any extra points, and worse could have you lose points. I would really refrain from changing the Data class like that.
If you would like to get experience with the NIO, then I suggest you use Max's book which has a great explaination of all the NIO stuff, and go through his book and try his examples/project.
But please don't do it in the Data class.
Mark
Eat that pie! EAT IT! Now read this tiny ad. READ IT!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 674 times.
Similar Threads
B&S: Server Shutdown
Accessing remote file?
suncertify.db.Data
data access
Is this against extensibility of application?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 14:58:16.