I am doing following: - creating an empty file - locking file - write to file - reading back the content
public class TempClass {
public static void main(String[] args) throws Exception{
File file = new File("c:/newfile.txt");
String content = "This is the text content123";
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = fileChannel.lock();
//write to file
fileChannel.write(ByteBuffer.wrap (contentInBytes));
//force any updates to this channel's file
fileChannel.force(false);
//reading back file contents
Double dFileSize = Math.floor(fileChannel.size());
int fileSize = dFileSize.intValue();
ByteBuffer readBuff = ByteBuffer.allocate(fileSize);
fileChannel.read(readBuff);
for (byte b : readBuff.array()) {
System.out.print((char)b);
}
lock.release();
}
}
However I can see the file is correctly written with the content I specified, but when I read it back, it prints square characters for all the actual characters in the file. That square character is char
equivalent of the byte 0:
System.out.print((char)((byte)0));
Whats wrong here?
When reading back the file, you did not reset the position in which the FileChannel is currently at, thus when performing
fileChannel.read(readBuff);
Nothing is being allocated to the buffer as the FileChannel is positioned at the end of the file (causing your print code to show the 0-initialized values).
Perform:
fileChannel.position(0);
to reset the FileChannel to the start of the file.