これについては、Java/Linuxのコンテキストでのみ説明します。
RandomAccessFile rand = new RandomAccessFile("test.log", "r");
VS
File file = new File("test.log");
作成後、ファイルの読み取りを最後まで開始します。
java.io.Fileの場合、ファイルを読み取る前に物理ファイルをmvまたは削除すると、ファイルの読み取り時にIOExceptionがスローされます。
public void readIOFile() throws IOException, InterruptedException { File file = new File("/tmp/test.log"); System.out.print("file created"); // convert byte into char Thread.sleep(5000); while (true) { char[] buffer = new char[1024]; FileReader fr = new FileReader(file); fr.read(buffer); System.out.println(buffer); } }
ただし、RandomFileAccessの場合、ファイルを読み取る前に物理ファイルをmvまたは削除すると、エラーや例外なしにファイルの読み取りが終了します。
public void readRAF() throws IOException, InterruptedException { File file = new File("/tmp/test.log"); RandomAccessFile rand = new RandomAccessFile(file, "rw"); System.out.println("file created"); // convert byte into char while (true) { System.out.println(file.lastModified()); System.out.println(file.length()); Thread.sleep(5000); System.out.println("finish sleeping"); int i = (int) rand.length(); rand.seek(0); // Seek to start point of file for (int ct = 0; ct < i; ct++) { byte b = rand.readByte(); // read byte from the file System.out.print((char) b); // convert byte into char } }
}
誰かが私に理由を説明できますか?ファイルのiノードとは何か関係がありますか?