2013-05-31 64 views
2

我正在製作一個包含文件複製的應用程序,但是當我瀏覽大型目錄(1000多個)文件並將它們複製到另一個文件夾時,它會使用290+ MB的RAM。在不創建FileOutputStream的情況下複製文件

那麼,有沒有辦法改變FileFileOutputStream而不創建FileOutoutStream類的新實例?

編輯:

這是我的Java 7 API版本。

Path source = FileSystems.getDefault().getPath(Drive.getAbsolutePath(), files[i].getName()); 
     Path destination = FileSystems.getDefault().getPath(Save); 
     try { 
     Files.copy(source, destination); 
     } catch (FileAlreadyExistsException e) { 
      File file = new File(Save + files[i]); 
      file.delete(); 
     } 

請記住,這是在一個正在測試1000個文件數的循環中。 隨着我使用270+ MB的RAM

+2

你正在關閉你的流? –

+0

哪個版本的Java?理想的答案取決於它。 Java 7有一個新的文件API,比之前的版本要好得多。 – fge

+0

礦是7u21。但使用7u17是一個選項 – zfollette

回答

7

不,您不能將FileOutputStream重定向到其他文件。

如果您使用的是Java 7,則可以使用新的Files類來複制文件。 Files.copy()方法可以爲你做大部分工作。

否則,請確認您正在關閉您的流。到Java 7的嘗試 - 與資源在此之前,它可能是這個樣子:

FileOutputStream out = null; 
try { 
    // Create the output stream 
    // Copy the file 
} catch (IOException e) { 
    // Do something 
} finally { 
    if (null != out) { 
     try { out.close(); } catch (IOException) { } 
    } 
} 
+0

+1,因爲OP說他在使用Java 7!然後你可以提到'Files.copy()' – fge

+0

你也需要將'close()'調用包裝在try-catch塊中以確保安全。這導致Java 7的抑制異常。 –

+0

@fge - 我暗示過Files類,但是你明白地提到Files.copy()會更清楚。新增了Files.copy()的明確提及。 –

0

如何從Java 7的一些NIO2?

Path source = // ... 
Path target = // ... 
Files.copy(source, target);  

有關詳細信息,請參閱javadoc的Files.copy(...)。另請參閱可選參數CopyOption

相關問題