在不创建FileOutputStream的情况下复制文件

zfo*_*tte 2 java file-io java-7

我正在制作一个包含文件复制的应用程序,但是当我浏览一个大目录(1000+)文件并将它们复制到另一个文件夹时,它使用290+ MB的RAM.

那么,有没有办法改变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();
        }
Run Code Online (Sandbox Code Playgroud)

请记住,这是在一个for循环中,正在测试1000多个文件计数.使用当前的方法,我使用270+ MB的RAM

And*_*mas 7

不,您无法将FileOutputStream重定向到其他文件.

如果您使用的是Java 7,则可以使用新的Files类来复制文件.这些Files.copy()方法可以为您完成大部分工作.

否则,请验证您是否正在关闭流.在Java 7的try-with-resources之前,它可能看起来像这样:

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 ) { }
    }
}
Run Code Online (Sandbox Code Playgroud)