操作的复杂程度如何改变文件名?

时间:2016-11-24 09:18:22

标签: java

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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