Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 输入流读取大文件非常慢,为什么?_Java_File Upload_File Io_Inputstream_Large Files - Fatal编程技术网

Java 输入流读取大文件非常慢,为什么?

Java 输入流读取大文件非常慢,为什么?,java,file-upload,file-io,inputstream,large-files,Java,File Upload,File Io,Inputstream,Large Files,我正在尝试提交一个500 MB的文件。 我可以加载它,但我想提高性能。 这是慢代码: File dest = getDestinationFile(source, destination); if(dest == null) return false; in = new BufferedInputStream(new FileInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(dest)); b

我正在尝试提交一个500 MB的文件。 我可以加载它,但我想提高性能。 这是慢代码:

File dest = getDestinationFile(source, destination);
if(dest == null) return false;

in = new BufferedInputStream(new  FileInputStream(source));
out = new BufferedOutputStream(new  FileOutputStream(dest));
byte[] buffer = new byte[1024 * 20];
int i = 0;

// this while loop is very slow
while((i = in.read(buffer)) != -1){
   out.write(buffer, 0, i); //<-- SLOW HERE
   out.flush();
}
File dest=getDestinationFile(源、目标);
如果(dest==null)返回false;
in=新的BufferedInputStream(新的FileInputStream(源));
out=新的BufferedOutputStream(新文件输出流(dest));
字节[]缓冲区=新字节[1024*20];
int i=0;
//这个while循环非常慢
而((i=in.read(buffer))!=-1){

out.write(缓冲区,0,i);//不应在循环中刷新。 您正在使用BufferedOutputStream。这意味着在“缓存”一些数据之后,它会将数据刷新到文件中。 您的代码只是在写入少量数据后刷新数据,从而降低了性能

试着这样做:

while((i = in.read(buffer)) != -1){
out.write(buffer, 0, i); <-- SLOW HERE
}
out.flush();
在我的版本中,您只需读取一个字节(无整数)。读取文档:

这个方法返回int,但这只是一个字节),但不需要读取整个缓冲区(所以您不必担心它的大小)。


可能您应该阅读更多关于流的内容,以便更好地理解如何处理它们。

我会将
移出.flush()
循环之外,但无论如何,代码在我看来还行……您称之为“慢”是什么?非常感谢你们,我将测试我的代码,看看会发生什么,顺便问一下,什么是好的缓冲区大小?我不想使用太多,但同时也不能太少。原来是byte[]buffer=new byte[1000],看起来太小了。感谢你们的输入。如果我要删除缓冲区[]数组,如何在out.write()部分中打印?它将创建一个错误,因为我以前创建的缓冲区数组不存在文件dest=getDestinationFile(source,destination);if(dest==null)返回false;in=new BufferedInputStream(new FileInputStream(source));out=new BufferedOutputStream(new FileOutputStream(dest));while((i=in.read())!=-1){out.write(buffer,0,i);我很抱歉:我在我的示例中犯了一个错误。没有编辑,所以您可以测试它谢谢您alex的回答…抱歉,太晚了!谢谢sjuan76 thx花时间帮助回答这个问题。
File dest = getDestinationFile(source, destination);
if(dest == null) return false;

in = new BufferedInputStream(new  FileInputStream(source));
out = new BufferedOutputStream(new  FileOutputStream(dest));

int i;
while((i = in.read()) != -1){
   out.write(i);
}
out.flush();