我正在编写一个程序部分,简单地将一个文件从源文件复制到目标文件。代码运行正常,但如果有一个大文件,则复制过程将在目标文件达到4.3 GB后结束,但有一个例外。例外情况是“文件太大了”,看起来像这样:
java.io.IOException: Die Datei ist zu groß
at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
at sun.nio.ch.FileDispatcherImpl.write(FileDispatcherImpl.java:60)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:211)
at java.nio.channels.Channels.writeFullyImpl(Channels.java:78)
at java.nio.channels.Channels.writeFully(Channels.java:101)
at java.nio.channels.Channels.access$000(Channels.java:61)
at java.nio.channels.Channels$1.write(Channels.java:174)
at java.nio.file.Files.copy(Files.java:2909)
at java.nio.file.Files.copy(Files.java:3069)
at sample.Controller.copyStream(Controller.java:318)
生成它的方法如下:
private void copyStream(File src, File dest){
try {
FileInputStream fis = new FileInputStream(src);
OutputStream newFos = java.nio.file.Files.newOutputStream(dest.toPath(),StandardOpenOption.WRITE);
Files.copy(src.toPath(),newFos);
newFos.flush();
newFos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我也尝试使用java.io文件输出流,并以千字节的方式编写,但也发生了同样的事情。如何复制或创建大于4.3 GB的文件?除了java之外,有没有可能用其他语言?这个程序是在Linux (Ubuntu LTS 16.04)上运行的。
提前谢谢。
编辑:
非常感谢你们的帮助。正如您所说,文件系统是问题所在。在我将文件系统格式化为exfat之后,它工作得很好。
发布于 2018-09-12 01:54:05
POSIX (以及Unix)系统被允许对路径施加最大长度(从File.getPath()
或路径的组件(最后一个可以通过File.getName()
获得))。由于文件的长名称,您可能会看到此问题。
在这种情况下,文件open
操作系统调用将失败,并显示ENAMETOOLONG
error code。
但是,消息"File too File“通常与”EFBIG“错误代码相关。这更有可能是由write
系统调用导致的:
试图写入的文件超出了取决于实现的最大文件大小或进程的文件大小限制。
可能正在打开文件以进行附加,并且文件末尾隐含的lseek会给出EFBIG
错误。
最后,如果它必须对你的RAM做一些事情,你可以尝试其他的复制方法。
另外,另一种选择可能是磁盘已满。
要复制文件,基本上有四种方法,事实证明streams在基本级别上是最快的:
使用streams复制:
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
使用Java NIO类进行复制:
private static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
Copy with Apache Commons IO FileUtils:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
和您使用Java7和Files类的方法:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
编辑1:根据评论中的建议,这里有三个SO问题,它们涵盖了这个问题,并解释了更好地复制的四种不同方法:
感谢@jww指出
https://stackoverflow.com/questions/52281384
复制相似问题