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();
Looks like you’re trying to download a binary file using HTTP protocol. This can actually be done in much easier way:
In steps:
URLpointing to a resource you want to download.openStream()to read the file byte-by-byte. The underlyingURLimplementations handles sockets,Content-length, etc.inputtooutput. I am usingIOUtilsfrom Apachecommons-ioto avoid boring and error-prone copying in a loop.inputto close the actual socket (maybe it happens implicitly once the streams ends?) andoutputto 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.