从互联网下载.txt文件

时间:2012-12-09 06:33:10

标签: android url text storage

  

可能重复:
  File download with android

如何从指定网址的互联网上下载.txt文件并将其保存到Android手机中?它可以保存到内部存储,SD存储或应用程序可以使用的任何地方。

我用于加载URL WebViews测试的网址是http://base.google.com/base/products.txt

1 个答案:

答案 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());
}