0

就像标题一样,我只是想下载一个 test.txt 文件,下面的 url 并将其保存在内部,最好是在 drawable 中。

我一直在尝试修改它以使其正常工作,但收效甚微,我不断收到“无法下载空”错误

int count;          
try {
    URL url = new URL("https://www.darkliteempire.gaming.multiplay.co.uk/testdownload.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 + "/test.txt");
    byte data[] = new byte[1024];
    long total = 0;
    int progress = 0;

    while ((count = is.read(data)) != -1) {
        total += count;

        int progress_temp = (int) total * 100 / lenghtOfFile;

        fos.write(data, 0, count);
    }

    is.close();
    fos.close();
} catch (Exception e) {
    Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
}

必须有一个更简单的方法来做到这一点?文件本身很小,可能只有 3 或 4 行文本,所以我不需要任何花哨的东西

4

2 回答 2

1

请更新您的以下代码行并编写有效的网址。

URL url = new URL("https://www.http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");

编写有效的 url 后,您的代码行如下所示。

URL url = new URL("http://www.darkliteempire.gaming.multiplay.co.uk/testdownload.txt");

它会解决你的问题。

于 2012-12-14T13:31:26.560 回答
0

使用AQuery 库你会得到一些非常简单的东西。此外,您还将获得其他很酷的功能来缩短您的代码。

http://code.google.com/p/android-query/wiki/AsyncAPI

String url = "https://picasaweb.google.com/data/feed/base/featured?max-results=16";             

File ext = Environment.getExternalStorageDirectory();
File target = new File(ext, "aquery/myfolder/photos.xml");              
aq.progress(R.id.progress).download(url, target, new AjaxCallback<File>(){            
        public void callback(String url, File file, AjaxStatus status) {                    
                if(file != null){
                        showResult("File:" + file.length() + ":" + file, status);
                }else{
                        showResult("Failed", status);
                }
        }            
});
于 2012-12-14T13:28:51.530 回答