Skip to content
Advertisement

Write a binary downloaded file to disk in Java

I have a software that allow to write add-on in javascript files (.js) that allow to use Java function (I don’t know if this is common, I never saw java call in javascript file before)

I need to download a binary file from a webserver and write it to the hard drive. I tried the following code:

baseencoder = new org.apache.commons.codec.binary.Base64();
url = new java.net.URL("https://server/file.tgz");

urlConnect = url.openConnection();
urlConnect.setDoInput(true);
urlConnect.setDoOutput(true);
urlConnect.setRequestProperty("authorization","Basic "+ java.lang.String(baseencoder.encodeBase64(java.lang.String( username + ":" + password ).getBytes())));
urlConnect.setRequestProperty("content-type","application/x-www-form-urlencoded");

is = new java.io.DataInputStream(urlConnect.getInputStream());
fstream = new FileWriter("C:\tmp\test.tgz");
out = new BufferedWriter(fstream);
while((data = is.read()) != -1){
    out.write(data);
}

out.close();
is.close();

The resulting file is no longer a valid gzip archive. I’m sorry if I did a huge error but I’m not a programmer and don’t know Java too much.

Advertisement

Answer

Don’t use a FileWriter – that’s trying to convert the data into text.

Just use FileOutputStream.

byte[] buffer = new byte[8 * 1024];

InputStream input = urlConnect.getInputStream();
try {
  OutputStream output = new FileOutputStream(filename);
  try {
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1) {
      output.write(buffer, 0, bytesRead);
    }
  } finally {
    output.close();
  }
} finally {
  input.close();
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement