2014-02-14 67 views
1

我有一個保存Java文件

File file = new File("/home/aa.db"); 

然後我打電話file.delete();

但我喜歡以前保存此文件在其他位置的其他名字刪除。 - 如何在沒有任何可視化工具的情況下在代碼中執行操作?

我需要一個副本 - 因爲我需要刪除init文件。重命名不會做的事

+2

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy –

+0

爲什麼不直接重命名呢? http://stackoverflow.com/questions/1158777/renaming-a-file-using-java – doctorlove

+0

我有添加導入nio.file;比我嘗試文件。 (但沒有副本)比我寫java.nio.file。 (但是這裏也沒有靜態方法的副本)=( – curiousity

回答

1

這裏移動文件到新目錄的樣本 -

File file = new File("/home/aa.db"); 
File dir = new File("dir"); 

if (file.renameTo(new File(dir, file.getName()))) { 
    // processing here 
} 

相關的例子:

import java.io.File; 

public class Example { 
    public static void main(String[] args) { 

     File file = new File("C://aa.db"); 
     File tmpFile = new File("C://temp", file.getName()); 

     if(file.renameTo(tmpFile)) { 
      if(tmpFile.delete()) { 
       System.out.println(tmpFile.getName() + " was deleted!"); 
      } else { 
       System.out.println("Delete operation failed."); 
      } 
     } 
    } 
} 

輸出: aa.db was deleted!

0

閱讀文件的數據(您的需要)在InputStream然後使用的File

public static long copy(InputStream in,Path target,CopyOption... options) 
       throws IOException 

副本從輸入流中的文件中的所有字節此功能。返回時,輸入 流將在流結束處。

在此之前,首先需要創建要複製數據的目標路徑。