我正在执行以下操作: - 创建一个空文件 - 锁定文件 - 写入文件 - 读回内容
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();
}
}
但是我可以看到文件是用我指定的内容正确写入的,但是当我读回它时,它会为文件中的所有实际字符打印方形字符。该方形字符char
相当于字节 0:
System.out.print((char)((byte)0));
这里有什么问题?