android下载文件损坏

xxslljrj  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(377)
btnShowProgress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                download();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}
public void download() throws IOException {
    URL url = new URL("URL");
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        String PATH = Environment.getExternalStorageDirectory()
                        + "/download/";
        File file = new File(PATH);
        file.mkdirs();
        String fileName = "Dragonfly";
        File outputFile = new File(file, fileName);
        FileOutputStream fos = new FileOutputStream(outputFile);
        InputStream is = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) > 0) {
            fos.write(buffer, 0, len1);
        }
        fos.flush();
        fos.close();
        is.close();

我使用该代码从自己的服务器下载一个文件,但文件总是以9,3kb下载(即使文件大小较小,如2kb),并且无法打开该文件。

xoefb8l8

xoefb8l81#

这是我的应用程序更新下载程序代码。对我来说很有用:

URL url = new URL(mUpdateUrl);
Log.d(LOG_TAG, "Connect to: " + mUpdateUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

int response = connection.getResponseCode();

if(response == 200)
{
    BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
    FileOutputStream fs = new FileOutputStream(filename);
    BufferedOutputStream out = new BufferedOutputStream(fs);
    byte [] buffer = new byte[16384];

    int len = 0;
    while ((len = in.read(buffer, 0, 16384)) != -1)
        out.write(buffer, 0, len);

    out.flush();
    in.close();
    out.close();
} else {
    Log.d(LOG_TAG, "Server return code: " + response + ", url: " + url);
    connection.disconnect();
    return null;
}

connection.disconnect();
return filename;

相关问题