0

我需要通过传递名称和 url 下载文件的功能,以便我可以在 android 应用程序中下载一系列文件。

所以继续创建这样的东西:

public void doDownload (String fileName, String url){
    File root = android.os.Environment.getExternalStorageDirectory();               
    File dir = new File (root.getAbsolutePath() + "/Content/"); 
    if(dir.exists()==false) {
        dir.mkdirs();
    }

    try{
        URL url = new URL(url);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        Log.i("ANDRO_ASYNC", "Lenght of file: " + fileLength);

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(dir + fileName);   
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;

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

        output.flush();
        output.close();
        input.close();
    }catch(Exception e){
    }
} 

XML:添加权限

现在当我调用这个函数时:

doDownload(String img.png, String http://server.com);

它不返回任何文件。这里有什么问题?

4

1 回答 1

0

另一种选择是使用下载管理器下载文件。您可以尝试使用下载管理器。请参阅 android 开发者网站。检查此链接:http: //developer.android.com/reference/android/app/DownloadManager.html

于 2013-03-21T05:53:26.423 回答