我需要使用Java下载文件。我可以使用此代码下载文本文件。但我在下载图像[数据]文件时遇到问题。它们写入磁盘已损坏。我在这做错了什么?
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();
答案 0 :(得分:2)
看起来您正在尝试使用HTTP协议下载二进制文件。实际上,这可以通过更简单的方式完成:
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();
分步骤:
URL
。openStream()
逐字节读取文件。基础URL
实现处理套接字,Content-length
等input
的内容复制到output
。我正在使用Apache IOUtils
中的commons-io
来避免在循环中出现无聊且容易出错的错误。input
来关闭实际的套接字(可能一旦流结束就会隐式发生?)和output
来刷新缓冲区。请注意,由于您基本上是逐字节复制数据,因此正确传输了文本文件(与编码无关)和二进制文件。