【问题标题】:file-size difference while downloading file下载文件时文件大小差异
【发布时间】:2016-07-05 12:50:36
【问题描述】:

我正在开发一个 Java 文件下载器,所以我刚刚下载了一个带应用程序和不带应用程序的视频文件,所以我看到了这些文件之间的文件大小差异。而且我无法打开使用我的 Java 应用程序下载的文件。当我使用 Notepad++ 打开它们时,我看到里面是随机生成的符号。我做错了什么?

http://i.imgur.com/lKaofVg.png - 在这里,您可以在那里看到随机生成的问号。 http://i.imgur.com/8bLC2R7.png - 但在原始文件中,它们不存在。 http://i.imgur.com/H3MGgwl.png - 这是文件大小,我只是为生成的文件添加了“+”。

这是我的代码:

        String currentRange = "bytes=0-"+num*13107200;
        System.out.println(num + " is executing");
        URL file = new URL(url);
        FileOutputStream stream = new FileOutputStream("tmp"+num+".mp4"); 
        HttpURLConnection urlConnection = (HttpURLConnection) file.openConnection();
        urlConnection.setRequestProperty("Range", currentRange);
        urlConnection.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                urlConnection.getInputStream()));
        String inputLine;

        final PrintStream printStream = new PrintStream(stream);
        while ((inputLine = in.readLine()) != null)
            printStream.println(inputLine);
        in.close();
        printStream.close();

【问题讨论】:

  • 不要使用 Readers/Writers/PrintStreams 处理二进制文件,它们仅用于文本数据。使用原始流。
  • mp4 文件是二进制文件。如果你用文本编辑器打开一个文本,你不能期望看到可读的文本。而且由于它是二进制的,因此您不应该使用允许阅读文本的阅读器来下载它。使用输入流。请注意,由于您只想按原样下载文件,因此适用于任何文件,包括文本文件。
  • readLine() 在每个换行符处拆分数据。不要那样做,你正在读取原始二进制数据。为什么你用notepad++打开一个视频文件却惊讶地看到“随机生成的符号”?你还期待什么?
  • @f1sh 我只是想看看两个文件之间的区别。

标签: java


【解决方案1】:

感谢这个问题,我使用这段代码解决了问题:Reading binary file from URLConnection 和 @piet.t

InputStream input = urlConnection.getInputStream();
            byte[] buffer = new byte[4096];
            int n = - 1;
            while ( (n = input.read(buffer)) != -1) 
            {
                stream.write(buffer, 0, n);
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2019-01-20
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2010-10-23
    相关资源
    最近更新 更多