2013-08-02 32 views
0

我編寫了一個程序,用於在我的PC中搜索具有給定擴展名的文件。現在我想添加一件事。我希望我的程序將這些文件複製到我個人電腦上的特定位置。這裏是我的代碼示例: -將搜索到的文件複製到特定位置

Finder(String pattern) 
    { 
     matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); 
    } 

    // Compares the pattern against 
    // the file or directory name. 
    void find(Path file) { 
     Path name = file.getFileName(); 
     if (name != null && matcher.matches(name)) { 
      System.out.println(file); 
      String s = new String(name.toString()); 
      //System.out.println(s); 
      File f = new File(s); 
      //System.out.println(f.getAbsolutePath()); 
      FileInputStream fileInputStream = null; 
+0

這裏的問題究竟是什麼? – Matthias

+0

檢查[此線程](http://stackoverflow.com/questions/1146153/copying-files-from-one-directory-to-another-in-java) –

+0

我想複製所有駐留在我的文本文件個人電腦,我的pendrive。我的程序正在成功搜索所有文本文件,現在我想複製這些..我怎麼能做到這一點? – Vicky

回答

0

一旦你的FileInputStream對你是要複製的文件要複製,您可以創建FileOutputStream小號輸出到地方的文件。然後,使用一個循環像下面複製的文件:

byte temp; 
while ((temp = fileInputStream.read()) != -1) 
    fileOutputStream.write(temp); 
0

有很多新的方法可以使用FileVistitor界面遍歷文件樹。點擊here

public static void copyFile(File sourceFile, File newDirectory) throws IOException { 
    File destFile = new File(newDirectory, sourceFile.getName()); 
    if(!destFile.exists()) { 
     destFile.createNewFile(); 
    } 

    FileChannel source = null; 
    FileChannel destination = null; 
    try { 
     source = new FileInputStream(sourceFile).getChannel(); 
     destination = new FileOutputStream(destFile).getChannel(); 
     destination.transferFrom(source, 0, source.size()); 
    } 
    finally { 
     if(source != null) { 
      source.close(); 
     } 
     if(destination != null) { 
      destination.close(); 
     } 
    } 
} 

定義要在參數過於移動文件「newDirectory」目錄

0

中有沒有問題:接近符合您的標準文件後,使用一些高performanced新的IO移動它你的問題! 如果你問如何複製文件,您可以選擇:

  • 使用java.nio.file.Files.copy()方法。這是較好的,因爲你沒有給自己複製數據時,可以使用路徑,它是在標準庫
  • 使用流和數據複製自己被其他的答案的建議

  • 有像調用命令其他方式系統複製

相關問題