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.
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.