-1

当我尝试从服务器下载文件时,它会丢失一些字节!并显示为损坏的文件。在我尝试从 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();
            }
        }
    }
4

1 回答 1

0

是的,问题在于使用 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) {}
于 2014-10-21T13:18:29.217 回答