SDK
SDK

Reputation: 175

cannot download data files using Java

I need to download a file using Java. I can use this code to download text files. But I have a problem downloading image[data] files. They are written in to the disk corrupted. What have I done here wrong?

FileOutputStream fileOutputStream = new FileOutputStream(url
                .getPath().substring(url.getPath().lastIndexOf("/") + 1));
BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
String line = "";
long l = 0;
while (!(line = bufferedReader.readLine()).isEmpty()) {
    System.out.println(line);
    if (line.contains("Content-Length:")) {
        l = Long.parseLong(line.substring(
                "Content-Length:".length()).trim());
    }
}

byte[] bytes = new byte[socket.getSendBufferSize()];
BufferedWriter bufferedWriter = new BufferedWriter(
        new OutputStreamWriter(fileOutputStream));
int x = 0;
long fullLength = 0;
int length = 0;
DataInputStream dataInputStream = new DataInputStream(
        socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(
        fileOutputStream);
while (fullLength < l
        && (length = dataInputStream.read(bytes)) != -1) {
    dataOutputStream.write(bytes, 0, length);

    System.out.print(length + " ");
    bufferedWriter.flush();
    fullLength += length;
}

fileOutputStream.flush();
bufferedWriter.close();
socket.close();

Upvotes: 0

Views: 415

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

Looks like you're trying to download a binary file using HTTP protocol. This can actually be done in much easier way:

final URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/94/Giewont_and_Wielka_Turnia.jpg");  //1
final InputStream input = url.openStream();  //2
final OutputStream output = new BufferedOutputStream(new FileOutputStream("giewont.jpg")); //3
IOUtils.copy(input, output);  //4
input.close();  //5
output.close();

In steps:

  1. Create URL pointing to a resource you want to download.
  2. openStream() to read the file byte-by-byte. The underlying URL implementations handles sockets, Content-length, etc.
  3. Create an empty file to save data to.
  4. Copy the contents of input to output. I am using IOUtils from Apache commons-io to avoid boring and error-prone copying in a loop.
  5. Close both streams. You need to close the input to close the actual socket (maybe it happens implicitly once the streams ends?) and output to flush the buffers.
  6. ...that's it!

Note that since you are basically copying the data byte-by-byte, both text files (irrespective to encoding) and binary files are transferred correctly.

Upvotes: 2

Related Questions