gpt4 book ai didi

java - 安卓下载文件损坏

转载 作者:行者123 更新时间:2023-11-29 21:12:40 26 4
gpt4 key购买 nike

    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)并且无法打开文件。

最佳答案

这是我的应用程序更新的下载器代码。它对我有用:

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;

关于java - 安卓下载文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22326796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com