无法使用Java下载数据文件

时间:2012-01-21 11:31:57

标签: java file sockets stream

我需要使用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();

1 个答案:

答案 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();

分步骤:

  1. 创建指向您要下载的资源的URL
  2. openStream()逐字节读取文件。基础URL实现处理套接字,Content-length
  3. 创建一个空文件以保存数据。
  4. input的内容复制到output。我正在使用Apache IOUtils中的commons-io来避免在循环中出现无聊且容易出错的错误。
  5. 关闭两个流。你需要关闭input来关闭实际的套接字(可能一旦流结束就会隐式发生?)和output来刷新缓冲区。
  6. ......就是这样!
  7. 请注意,由于您基本上是逐字节复制数据,因此正确传输了文本文件(与编码无关)和二进制文件。