【Java】對檔案或檔案夾進行重新命名

來源:互聯網
上載者:User

標籤:.net   方法   port   系統   alt   檔案的   comm   blog   因此   

在Java中,對檔案或檔案夾進行重新命名是很簡單的,因為Java的File類已經封裝好renameTo的方法。

修改檔案或者檔案夾的名字都使用這個方法。例如如下的程式:

 

[java] view plain copy 
  1. import java.io.*;  
  2. public class renameTest {  
  3.   
  4.     public static void main(String[] args) {  
  5.         //想命名的原檔案的路徑  
  6.         File file = new File("f:/a/a.xlsx");  
  7.         //將原檔案更改為f:\a\b.xlsx,其中路徑是必要的。注意  
  8.         file.renameTo(new File("f:/a/b.xlsx"));  
  9.         //想命名的原檔案夾的路徑  
  10.         File file1 = new File("f:/A");  
  11.         //將原檔案夾更改為A,其中路徑是必要的。注意  
  12.         file1.renameTo(new File("f:/B"));  
  13.     }  
  14.   
  15. }  

 

一旦運行,則會把f:/a/a.xlsx先更名為f:/a/b.xlsx,然後會把f:/A這個檔案夾更名為f:/B。

請注意在Windows下,檔案夾與檔案名稱是不區分大小寫。

因此f:/A與f:/a其實是一碼事。

其實檔案夾改名還可以寫得更簡短點,連這個File類的聲明都不要了。

把f:/a/a.xlsx更名為f:/a/b.xlsx直接這樣寫得了:

 

[java] view plain copy 
  1. import java.io.*;  
  2. public class renameTest {  
  3.   
  4.     public static void main(String[] args) {  
  5.         //把f:/a/a.xlsx原檔案重新命名為f:/a/b.xlsx,其中路徑是必要的。注意  
  6.         new File("f:/a/a.xlsx").renameTo(new File("f:/a/b.xlsx"));  
  7.     }  
  8.   
  9. }  

然後,值得注意的是,更名檔案的前面的父路徑必須相同,即,如下的方式是不對的:

 

 

[java] view plain copy 
  1. import java.io.*;  
  2. public class renameTest {  
  3.   
  4.     public static void main(String[] args) {  
  5.         new File("f:/a/a.xlsx").renameTo(new File("c:/a/b.bmp"));  
  6.     }  
  7.   
  8. }  

 

執行之後renameTo方法返回false,然後系統的檔案夾沒有任何改變。

【Java】對檔案或檔案夾進行重新命名

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.