gpt4 book ai didi

java - ArrayIndexOutOfBoundsException 写入文件

转载 作者:可可西里 更新时间:2023-11-01 16:34:11 26 4
gpt4 key购买 nike

我正在尝试通过 HTTP 连接下载二进制文件。但是,我的代码抛出 java.io.FileOutputStream.write(Unknown Source) 错误。我不确定我做错了什么。

public void GetFileDownload(String URI) throws IOException{ 
/*
* Given a URI this method will grab the binary data from that page over the http protocol
*/
URL inputURI;
HttpURLConnection connect;
BufferedReader input;
inputURI = new URL(URI);
connect = (HttpURLConnection) inputURI.openConnection();
connect.setReadTimeout(10000);
connect.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401");
connect.setRequestMethod("GET");
input = new BufferedReader(new InputStreamReader(connect.getInputStream()));
byte[] buffer = new byte[4096];
int n = - 1;

String file = "test";
int i = 0;
OutputStream output = new FileOutputStream(file);
while (i != buffer.length - 1){
i++;
System.out.print(buffer[i]);
}
while ((n = input.read()) != -1)
output.write(buffer, 0, n);
output.close();
}

最佳答案

     String link = "<YOUR_URL>/" + "download.jar"; // jar is binary 
String fileName = "download.jar";
URL url = new URL( link );
HttpURLConnection http = (HttpURLConnection)url.openConnection();
InputStream input = http.getInputStream();
byte[] buffer = new byte[2048];
int n = -1;
OutputStream output = new FileOutputStream( new File( fileName ));
while ((n = input.read(buffer)) != -1) { //make sure your to check -1 and target buffer to read from
output.write( buffer, 0, n );
}
output.close();

以上代码抛出 IOException,所以你需要处理异常。

关于java - ArrayIndexOutOfBoundsException 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16783018/

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