java中給檔案改名

來源:互聯網
上載者:User

1.File   oldf   =   new   File(oldFileName);
File   newf   =null;

if   (oldf   !=   null)   {
    newf   =   new   File(newFileName);
    oldf.renameTo(newf);
}

 

 

2. 以前我一直以為File#renameTo(File)方法與OS下面的 move/mv 命令是相同的,可以達到改名、移動檔案的目的。不過後來經常發現問題:File#renameTo(File)方法會返回失敗(false),檔案沒有移動,又查不出原因,再後來乾脆棄用該方法,自己實現一個copy方法,問題倒是再也沒有出現過。

  昨天老闆同學又遇到這個問題,File#renameTo(File)方法在windows下面工作的好好的,在linux下偶爾又失靈了。回到家我掃了一遍JDK中File#renameTo(File)方法的原始碼,發現它調用的是一個本地的方法(native method),無法再跟蹤下去。網上有人說該方法在window下是正常的,在linux下面是不正常的。這個很難說通,SUN不可能搞出這種平台不一致的代碼出來啊。

  後面在SUN的官方論壇上看到有人提到這個問題“works on windows, don't work on linux”,後面有人回複說是“file systems”不一樣。究竟怎麼不一樣呢?還是沒有想出來...

  後面在一個論壇裡面發現了某人關於這個問題的闡述:

  In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case.

  The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:

  終於明白咯。

  做個實驗:

  

以下是程式碼片段:
1 File sourceFile = new File("c:/test.txt");
  2 File targetFile1 = new File("e:/test.txt");
  3 File targetFile2 = new File("d:/test.txt");
  4 System.out.println("source file is exist? " + sourceFile.exists() + ", source file => " + sourceFile);
  5 System.out.println(targetFile1 + " is exist? " + targetFile1.exists());
  6 System.out.println("rename to " + targetFile1 + " => " + sourceFile.renameTo(targetFile1));
  7 System.out.println("source file is exist? " + sourceFile.exists() + ", source file => " + sourceFile);
  8 System.out.println(targetFile2 + " is exist? " + targetFile2.exists());
  9 System.out.println("rename to " + targetFile2 + " => " + sourceFile.renameTo(targetFile2));
  結果:

  

以下是程式碼片段:
1 source file is exist? true, source file => c:\test.txt
  2 e:\test.txt is exist? false
  3 rename to e:\test.txt => false
  4 source file is exist? true, source file => c:\test.txt
  5 d:\test.txt is exist? false
  6 rename to d:\test.txt => true

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.