0

我每 5 秒运行一次写入文件的任务,java 程序写入 test.txt 成功,但文本 file.txt lastModified 仍然是创建时间,而不是 lastModified 时间。我使用 strace 来查看问题所在。

strace 外壳:

strace -e msync -f -p 24036

Process 24036 attached with 19 threads - interrupt to quit
[pid 24054] msync(0x2aaaaf5e9000, 10000, MS_SYNC) = 0
[pid 24054] msync(0x2aaaaf5e9000, 10000, MS_SYNC) = 0
[pid 24054] msync(0x2aaaaf5e9000, 10000, MS_SYNC) = 0
[pid 24054] msync(0x2aaaaf5e9000, 10000, MS_SYNC) = 0
[pid 24054] msync(0x2aaaaf5e9000, 10000, MS_SYNC) = 0

java演示代码:

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Test2 {
    private static String file = "/home/fuyou/test/test.txt";

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    write();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
}

public static void write() throws Exception {
    RandomAccessFile randomAccessFile = new RandomAccessFile(new File(file), "rwd");
    FileChannel fileChannel = randomAccessFile.getChannel();
    MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 10000);
    int i=0;
    while (true) {
        if(++i>=126){
            i =1;
        }
        mappedByteBuffer.position(i);
        mappedByteBuffer.put((byte)i);
        System.out.println("write...");
        Thread.sleep(5000);
        mappedByteBuffer.force();

    }

}
}

当我在 Mac OSX10.9 中运行一些代码时,文件 lastModified 按预期每 5 秒更新一次,那么我的程序有什么问题?

操作系统是:

uname -a
Linux  2.6.18-164.el5 #1 SMP Tue Aug 18 15:51:48 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux

cat /etc/issue

Red Hat Enterprise Linux Server release 5.4 (Tikanga)
java version "1.6.0_23"
4

0 回答 0