我需要使用 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();
最佳答案
您似乎正在尝试使用 HTTP 协议(protocol)下载二进制文件。这实际上可以通过更简单的方式完成:
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
等。- 创建一个空文件来保存数据。
- 将
输入
的内容复制到输出
。我正在使用IOUtils
来自 Apachecommons-io
以避免循环中无聊且容易出错的复制。 - 关闭两个流。您需要关闭
输入
来关闭实际的套接字(也许它在流结束后隐式发生?)和输出
来刷新缓冲区。 - ...就是这样!
请注意,由于您基本上是逐字节复制数据,因此文本文件(无论编码如何)和二进制文件都会正确传输。
关于java - 无法使用Java下载数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8952625/