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

无法使用java.nio.channels.FileChannel读取文件,java,byte,nio,filechannel,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()) {

我正在做以下工作: -创建空文件 -锁定文件 -写入文件 -重读内容

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

这里有什么问题?

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

fileChannel.read(readBuff);
由于FileChannel位于文件末尾,因此未向缓冲区分配任何内容(导致打印代码显示0初始化值)

执行:

fileChannel.position(0);

要将FileChannel重置为文件的开头。

是的,很好,您只需将pin指向,我必须
FileChannel.position(0)
fileChannel.write()之后和
fileChannel.read(readBuff)之前有没有什么方法可以在锁定文件时删除该文件,因为我只想读取该文件,然后将其删除,而不允许其他人再次读取该文件。好的,在释放锁后使用
file.delete()
方法即可。。。我非常怀疑,如果锁释放和删除方法的位置紧随其后,某些程序会获得锁释放和删除方法之间的锁
FileChannel
保留用于对文件执行I/O操作,若要删除它,请使用
file
对象本身。这样做不好,对吗?我们不能保证这一点吗?无法安全地删除文件?还有别的办法吗?我认为这是可能的,因为如果有人在循环中连续运行代码访问文件,就可以获得对文件的这种控制?@Mahesha999嗯。。。我不清楚是否可以在打开FileChannel/FileLock时执行删除。。。找到答案的最好方法就是尝试一下。。。如果它有效,那么你就达到了你想要的目的,如果没有,那么最好的选择就是我前面所说的。