从url错误“java.io.FileNotFoundException:/ Users / Documents(没有这样的文件或目录)”下载文件

时间:2017-08-15 10:17:56

标签: android

我只是想将文件从网址http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true下载到我的系统,这里是我的代码

    getDirectory=(Button)findViewById(R.id.btn_newDirectory);
    getDirectory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view)
        {
            new DownloadingTask().execute();
        }
    });
    private class DownloadingTask  extends AsyncTask<Void,Void,Void>{
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL(fonturl);
            HttpURLConnection c = (HttpURLConnection)     
            url.openConnection();
            c.setRequestMethod("GET");
            c.connect();
            FileOutputStream fos = new FileOutputStream("/Users/Documents");
            Log.i("Download","complete");
            InputStream is = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
        }
            catch (Exception e) {
            e.printStackTrace();
            outputFile = null;
            Log.e("Error", "Download Error Exception " + e.getMessage());
        }

        return null;
    }
}

文件未下载但丢失错误下载错误异常/用户/文档(没有此类文件或目录)

1 个答案:

答案 0 :(得分:2)

没有&#34;用户/文件&#34;存储上的目录。让我稍微重写你的代码

getDirectory=(Button)findViewById(R.id.btn_newDirectory);
getDirectory.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view)
    {
        new DownloadingTask().execute();
    }
});
private class DownloadingTask  extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... voids) {
    try {
        URL url = new URL(fonturl);
        HttpURLConnection c = (HttpURLConnection)     
        url.openConnection();
        c.setRequestMethod("GET");
        c.connect();
        FileOutputStream fos = new FileOutputStream(new File(getFilesDir(),"Roboto-Regular.ttf")); // File you want to save to, It creates Roboto-Regular.ttf in your Internal Storage you got from "getFilesDir() method
        Log.i("Download","complete");
        InputStream is = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }
        fos.close();
        is.close();
    }
        catch (Exception e) {
        e.printStackTrace();
        outputFile = null;
        Log.e("Error", "Download Error Exception " + e.getMessage());
    }

    return null;
}}

此代码会将字体下载到您应用的内部存储空间中。如果您想将其保存到外部存储设备或获取更多信息,您可以试一试这篇文章: https://developer.android.com/training/basics/data-storage/files.html