无法在Android错误中创建目录

时间:2016-07-21 21:27:35

标签: android android-file android-download-manager

我正在尝试从服务器下载文件并将其存储在存储中,但代码会出错 - Unable to create directory。请检查错误

任务 - 文件从服务器下载,然后在android中的webview中加载。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = (WebView) findViewById(R.id.webView);
    try {
        webView.loadUrl("file://" + Environment.getExternalStorageDirectory() + "/sponsors/"+ "dddd.html");
    }
    catch (Exception e)
    {
        Toast.makeText(MainActivity.this, "File Doesn't Exist", Toast.LENGTH_SHORT).show();
    }
    try {
        myDownloadLast("http://192.168.76.1:8084/MyTest/dddd.html");
    }
    catch (Exception e)
    {
        Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show();
    }
}
public void myDownloadLast(String myURL) {

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myURL));
    request.setTitle("Updating TimeTable");
    request.setDescription("Please Wait");

    //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    String nameOfFile = URLUtil.guessFileName(myURL, null, MimeTypeMap.getFileExtensionFromUrl(myURL));

    File myFile = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("/sponsors/")));
    if(!myFile.exists()){
        myFile.mkdir();
    }
    try {
        request.setDestinationInExternalPublicDir(String.valueOf(myFile), nameOfFile);
    }
    catch (Exception e)
    {
        Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show();
    }
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            //Toast.makeText(getActivity(), "Download Complete", Toast.LENGTH_LONG).show();
            Toast.makeText(getApplicationContext(), "Update Complete\nFor Best Performance\nRestart The App", Toast.LENGTH_SHORT).show();
        }
    };
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

1 个答案:

答案 0 :(得分:1)

你的问题可能与一些嫌犯有关

确保拥有 Android Manifest

的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

另外,请参阅外部目录,其中包含以下内容:

String name = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DirectoryNameYouWant/" ;