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)并且无法打开文件。
答案 0 :(得分:2)
这是我的应用更新下载代码。它对我有用:
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;