1
如何在給定的URL從網上下載一個.txt文件,並將其保存到Android的手機?它可以保存到內部存儲,SD存儲或應用程序可以使用的任何地方。
我一直在使用與裝載URL網頁視圖測試的網址是http://base.google.com/base/products.txt
如何在給定的URL從網上下載一個.txt文件,並將其保存到Android的手機?它可以保存到內部存儲,SD存儲或應用程序可以使用的任何地方。
我一直在使用與裝載URL網頁視圖測試的網址是http://base.google.com/base/products.txt
這應該做的伎倆。它將文件下載到sdcard/Download/products.txt
。您可以在下面更改它。
try {
URL url = new URL("http://base.google.com/base/products.txt");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/products.txt");
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100/lenghtOfFile;
/*publishProgress("" + progress_temp); //only for asynctask
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}*/
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
}
初始化變量'progress'後引用了一個未知變量'count'。我安全地認爲'count'應該是'progress'? – Adam
對不起!添加'int count';它可以被訪問。編輯我的答案! – MrYanDao