gpt4 book ai didi

用于下载文件或 zip 文件的 Java 代码

转载 作者:行者123 更新时间:2023-12-01 16:32:47 24 4
gpt4 key购买 nike

我正在使用下面的代码下载文件,它对于小文件工作正常,但是当我尝试下载大小> 11GB的文件时,代码不起作用并给出java.lang.NegativeArraySizeException异常

public String downloadDirectory()
{

OutputStream myOut = null;
FileInputStream fileInputStream = null;
File downzip = new File(dirName+"/"+dir+".zip");


getServletResponse().setContentType("TEXT/HTML");
getServletResponse().setHeader("Content-Disposition","attachment; filename=\"" + dir +".zip" + "\"");
getServletResponse().setContentLength((int)downzip.length());
System.out.println("length "+(int)downzip.length());
//READ DATA FROM FILE

byte[] dataRead = new byte[(int)downzip.length()];
fileInputStream = new FileInputStream(downzip);
fileInputStream.read(dataRead,0,(int)downzip.length());
//WRITE DATA TO OUTFILE
myOut = getServletResponse().getOutputStream();


myOut.write(dataRead);

if (fileInputStream != null) {
fileInputStream.close();
}



}
catch(Exception e)
{
e.printStackTrace();
Execute.rmdirscript(dirName);
return "exception";
}
finally{
System.out.println("finally downloaddir");
if(myOut!=null){
try{
myOut.close();}
catch(Exception e){
e.printStackTrace();;
}
}
if (fileInputStream != null) {
try{
fileInputStream.close();}
catch(Exception e){
e.printStackTrace();;
}
}
}


}

错误出现在这一行:

byte[] dataRead = new byte[(int)downzip.length()];

对于大文件,值(int)downzip.length()变为负数,并给出java.lang.NegativeArraySizeException异常。

最佳答案

你没有循环尝试吗?像这样

 byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
out.write(data, 0, count);
}

关于用于下载文件或 zip 文件的 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12723895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com