Tôi có mã để sao chép tệp sang vị trí khác.Lỗi với NIO khi cố gắng sao chép tệp lớn
public static void copyFile(String sourceDest, String newDest) throws IOException {
File sourceFile = new File(sourceDest);
File destFile = new File(newDest);
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();
}
}
}
}
Trong khi sao chép khối nhỏ, giả sử, 300-400 Mb, mọi thứ hoạt động như ma thuật. Nhưng khi tôi cố gắng sao chép một tệp có kích thước 1,5 Gb thì không thành công. Ngăn xếp là:
run: 12.01.2011 11:16:36 FileCopier main SEVERE: Exception occured while copying file. Try again. java.io.IOException: Map failed at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:748) at sun.nio.ch.FileChannelImpl.transferFromFileChannel(FileChannelImpl.java:527) at sun.nio.ch.FileChannelImpl.transferFrom(FileChannelImpl.java:590) at FileCopier.copyFile(FileCopier.java:64) at FileCopier.main(FileCopier.java:27) Caused by: java.lang.OutOfMemoryError: Map failed at sun.nio.ch.FileChannelImpl.map0(Native Method) at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:745) ... 4 more BUILD SUCCESSFUL (total time: 0 seconds)
Tôi chưa làm việc với NIO chặt chẽ. Ông có thể giúp tôi không? Cảm ơn trước.
Hãy thử với Files.copy http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html nếu nó hoạt động có một cái nhìn xem trong src – oluies
Cảm ơn bạn. Nhưng tôi không muốn sử dụng thư viện của bên thứ ba trong trường hợp cụ thể này. –