操作的复杂如何更改文件名



我正在寻找从Java应用程序标记文件的方法(告诉我的程序正在使用该文件)。我正在考虑将某种类型的令牌添加到文件名的开头,我想知道这是否太慢了。请记住,这可能会在一秒钟内多次发生,因此时间效率很重要。

它真的很快,因为文件甚至不会更改。您的文件系统将根本不会读或写入文件,名称存储在其他地方

一个简单的文件重命名测试给出以下结果:

Renaming a file 10 times with Java takes 44 ms.
Renaming a file 100 times with Java takes 70 ms.
Renaming a file 1000 times with Java takes 397 ms.
Renaming a file 10000 times with Java takes 1339 ms.
Renaming a file 100000 times with Java takes 8452 ms.

假设您创建了/Users/UserName/test/文件夹,请尝试:

public class Test {
    public static void main(String[] args) throws IOException {
        testRename(10);
        testRename(100);
        testRename(1000);
        testRename(10000);
        testRename(100000);
    }
    public static void testRename(int times) throws IOException {
        String folderPath = "/Users/UserName/test/";
        File targetFile = new File(folderPath + "0");
        targetFile.createNewFile();
        long tic = System.nanoTime();
        Path path;
        for (int i = 0; i < times; i++) {
            String name = String.valueOf(i);
            path = Paths.get(folderPath + name);
            Files.move(path, path.resolveSibling(String.valueOf(i + 1)));
        }
        long tac = System.nanoTime();
        long result = (tac - tic) / 1000 / 1000;
        new File(folderPath + times).delete();
        System.out.println(String.format("Renaming a file %d times with Java takes %d ms.", times, result));
    }
}

最新更新