Reputation: 175
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
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:
URL
pointing to a resource you want to download.openStream()
to read the file byte-by-byte. The underlying URL
implementations handles sockets, Content-length
, etc.input
to output
. I am using IOUtils
from Apache commons-io
to avoid boring and error-prone copying in a loop.input
to close the actual socket (maybe it happens implicitly once the streams ends?) and output
to flush the buffers.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