如何从指定网址的互联网上下载.txt文件并将其保存到Android手机中?它可以保存到内部存储,SD存储或应用程序可以使用的任何地方。
我用于加载URL WebViews测试的网址是http://base.google.com/base/products.txt
答案 0 :(得分:1)
这应该可以解决问题。它将文件下载到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());
}