Compare text files by byte position
Hi All,
I am trying to copy data from one .txt file to another text file based on byte position. Simplest way to achieve this is use StringBuffer and Substring, but I am looking for better way. As these files are huge containing lot of records and I have to copy lot of data from one file to another based on byte position. It will be really great if any one can throw some light on this.
Sameer
Reading from channel with a ByteBuffer:
/*This example uses a ByteBuffer to read from a channel. The tricky part of this operation is to remember to properly set the buffer's position before and after a read.*/
try {
// Obtain a channel
ReadableByteChannel channel = new FileInputStream("infile").getChannel();
// Create a direct ByteBuffer; see also e158 Creating a ByteBuffer
ByteBuffer buf = ByteBuffer.allocateDirect(10);
int numRead = 0;
while (numRead >= 0) {
// read() places read bytes at the buffer's position so the
// position should always be properly set before calling read()
// This method sets the position to 0
buf.rewind();
// Read bytes from the channel
numRead = channel.read(buf);
// The read() method also moves the position so in order to
// read the new bytes, the buffer's position must be set back to 0
buf.rewind();
// Read bytes from ByteBuffer; see also
// e159 Getting Bytes from a ByteBuffer
for (int i=0; i<numRead; i++) {
byte b = buf.get();
}
}
} catch (Exception e) {
}
Writing to a Channel with a ByteBuffer:
/*It is necessary to use a ByteBuffer to write to a channel. This example retrieves bytes from an input stream and writes them to a channel using a ByteBuffer. The tricky part of this operation is to remember to properly set the buffer's position before and after a write.*/
try {
// Obtain a channel
WritableByteChannel channel = new FileOutputStream("outfilename").getChannel();
// Create a direct ByteBuffer;
// see also e158 Creating a ByteBuffer
ByteBuffer buf = ByteBuffer.allocateDirect(10);
byte[] bytes = new byte[1024];
int count = 0;
int index = 0;
// Continue writing bytes until there are no more
while (count >= 0) {
if (index == count) {
count = inputStream.read(bytes);
index = 0;
}
// Fill ByteBuffer
while (index < count && buf.hasRemaining()) {
buf.put(bytes[index++]);
}
// Set the limit to the current position and the position to 0
// making the new bytes visible for write()
buf.flip();
// Write the bytes to the channel
int numWritten = channel.write(buf);
// Check if all bytes were written
if (buf.hasRemaining()) {
// If not all bytes were written, move the unwritten bytes
// to the beginning and set position just after the last
// unwritten byte; also set limit to the capacity
buf.compact();
} else {
// Set the position to 0 and the limit to capacity
buf.clear();
}
}
// Close the file
channel.close();
} catch (Exception e) {
}