如何从服务器下载文件并将其保存在Android的SD卡中的特定文件夹中?

kum*_*eer 24 android android-input-method android-download-manager

我的Android应用程序中有一个要求.我需要以编程方式下载并保存SD卡特定文件夹中的文件.我开发了源代码,这是

String DownloadUrl = "http://myexample.com/android/";
     String fileName = "myclock_db.db";

    DownloadDatabase(DownloadUrl,fileName);

    // and the method is

public void DownloadDatabase(String DownloadUrl, String fileName) {
    try {
        File root = android.os.Environment.getExternalStorageDirectory();
        File dir = new File(root.getAbsolutePath() + "/myclock/databases");
        if(dir.exists() == false){
             dir.mkdirs();  
        }

        URL url = new URL("http://myexample.com/android/");
        File file = new File(dir,fileName);

        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager" , "download url:" +url);
        Log.d("DownloadManager" , "download file name:" + fileName);

        URLConnection uconn = url.openConnection();
        uconn.setReadTimeout(TIMEOUT_CONNECTION);
        uconn.setConnectTimeout(TIMEOUT_SOCKET);

        InputStream is = uconn.getInputStream();
        BufferedInputStream bufferinstream = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while((current = bufferinstream.read()) != -1){
            baf.append((byte) current);
        }

        FileOutputStream fos = new FileOutputStream( file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
        int dotindex = fileName.lastIndexOf('.');
        if(dotindex>=0){
            fileName = fileName.substring(0,dotindex);

    }
    catch(IOException e) {
        Log.d("DownloadManager" , "Error:" + e);
    }

}
Run Code Online (Sandbox Code Playgroud)

现在问题只是文件myclock_db.db保存在路径中的空文件.但我需要下载并保存特定文件夹中的文件内容.试过几种方法来获取文件下载,但我不能.

shi*_*tya 15

您的下载URL不是指向任何文件的链接.这是一个目录.确保它是一个文件并存在.还要检查logcat窗口中的错误日志.还有一个建议,它总是更好地在catch块而不是Logs中执行printStackTrace().它提供了更详细的错误视图.

改变这一行:

    URL url = new URL("http://myexample.com/android/");
Run Code Online (Sandbox Code Playgroud)

至:

    URL url = new URL("http://myexample.com/android/yourfilename.txt"); //some file url
Run Code Online (Sandbox Code Playgroud)

接下来,在catch块中,添加以下行:

e.printStackTrace();
Run Code Online (Sandbox Code Playgroud)

同样在目录路径中,它应该是这样的:

File dir = new File(root.getAbsolutePath() + "/mnt/sdcard/myclock/databases");
Run Code Online (Sandbox Code Playgroud)

代替

File dir = new File(root.getAbsolutePath() + "/myclock/databases");
Run Code Online (Sandbox Code Playgroud)

接下来,确保您已获得在Android清单中写入外部存储的权限.