2016-11-24 34 views
-3

我正在尋找從Java應用程序標記文件的方法(告訴我的程序該文件正在使用)。我正在考慮在文件名的開頭添加某種類型的令牌,我想知道這是否過程緩慢。請記住,這可能會在一秒內發生多次,所以時間效率非常重要。操作的複雜程度如何改變文件名?

+2

重命名文件是非常快的。 – Berger

+2

你甚至嘗試過重命名一個文件嗎?然後嘗試重命名100個文件?這很容易檢查你自己。 – AxelH

回答

0

它真的很快,因爲文件甚至沒有改變。你的文件系統將無法讀取或寫入所有,名稱存儲在其他地方的文件

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