【问题标题】:InputstreamReader not reading all bytes of data from URL: android?InputstreamReader 没有从 URL 读取所有字节的数据:android?
【发布时间】:2014-10-21 11:46:33
【问题描述】:

当我尝试从服务器下载文件时,它会丢失一些字节!并显示为损坏的文件。在我尝试从 URL 下载的代码下方。运行时也不例外。我在服务中使用它。 这些是我尝试的示例结果:

文件 1: 实际大小 = 73.2 kb 下载大小 = 68.7 kb

文件 2: 实际大小 = 147 kb 下载大小 = 137 kb

文件 3: 实际大小 = 125 kb 下载大小 = 116.8 kb

请帮助我找到我的代码所需的更正。 谢谢,

    InputStream stream = null;
    FileOutputStream fos = null;
    try {

        URL url = new URL(urlPath);
        stream = url.openConnection().getInputStream();
        InputStreamReader reader = new InputStreamReader(stream);
        fos = new FileOutputStream(output.getPath());
        int next = -1;
        while ((next = reader.read()) != -1) {
            fos.write(next);

        }
        // Successful finished
        Log.d("reaching", "reaching : DOWNLOAD FINISHED SUCCESSFULLY");

    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

【问题讨论】:

  • 除非您知道来源是文本,否则不要使用Reader,如果是,您应该使用Writer 来编写它。否则你应该使用输入和输出流。
  • 感谢@EJP 的帮助,当我更改为输入和输出流时它可以工作

标签: android file download inputstreamreader


【解决方案1】:

是的,问题在于使用 InputstreamReader 我使用 InputStream 而不是 @EJP 所说的那样。我修改了我的代码以从服务器下载文件

我在这里为访问此链接的人提供我的代码。可能对他们有帮助。

 try {

        URL url = new URL(urlPath);
        URLConnection conexion = url.openConnection();
        conexion.connect();

        int lenghtOfFile = conexion.getContentLength();
        Log.d("download", "Lenght of file: " + lenghtOfFile);

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new  FileOutputStream(Environment.getExternalStorageDirectory()+"/"+fileName);

        byte data[] = new byte[1024];


        int count= -1;

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2020-01-17
    • 2021-04-03
    • 2014-04-23
    • 1970-01-01
    • 2013-07-10
    • 2019-04-05
    相关资源
    最近更新 更多