Reputation: 778
I am trying to download a binary file over a http connection. However, my code throws a java.io.FileOutputStream.write(Unknown Source) error. I am not sure what I am doing wrong.
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();
}
Upvotes: 2
Views: 1848
Reputation: 310926
Your copy loop is wrong. It should be:
while ((n = input.read(buffer)) > 0)
{
output.write(buffer, 0, n);
}
You are causing an array index out of bounds condition.
Upvotes: 1
Reputation: 3794
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();
Above code throws IOException so you need to handle exception.
Upvotes: 1
Reputation: 5537
while ((n = input.read(buffer)) != -1)
You need to provide the target buffer to the read method.
Upvotes: 0