无法使用java.nio.channels.FileChannel读取文件

时间:2013-11-07 09:14:28

标签: java byte nio filechannel

我正在做以下事情:   - 创建一个空文件   - 锁定文件   - 写入文件   - 回读内容

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();
       }    

}

但是我可以看到文件是用我指定的内容正确编写的,但是当我读回来时,它会为文件中的所有实际字符打印方形字符。该方形字符等于字节0的char

System.out.print((char)((byte)0));

这里有什么问题?

1 个答案:

答案 0 :(得分:2)

当回读文件时,您没有重置FileChannel当前所处的位置,因此在执行时

fileChannel.read(readBuff);

由于FileChannel位于文件的末尾(导致打印代码显示0初始值),因此没有任何内容分配给缓冲区。

执行:

fileChannel.position(0);

将FileChannel重置为文件的开头。

相关问题