【问题标题】:i want to download a image from network but give this Exception :android.system.ErrnoException: open failed: ENOENT (No such file or directory)我想从网络下载图像但给出这个异常:android.system.ErrnoException:打开失败:ENOENT(没有这样的文件或目录)
【发布时间】:2020-02-29 11:49:10
【问题描述】:

我将权限放入 Manifest。 我想从 Internet 下载图像并将其存储在外部存储中。 图片链接没问题。 写入外部存储器时出现问题。

public class MainActivity extends AppCompatActivity {

    final static String DL_URL = "https://download.hipwallpaper.com/desktop/1920/1080/1/97/yE0qUN.jpg";
    public static Context context;
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        imageView = findViewById(R.id.image_view);
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},111);
    }

    public void onClick(View view) {

        MyTask task = new MyTask();
        task.execute(DL_URL);

    }


class MyTask extends AsyncTask<String,String,String>{



    @Override
    protected String doInBackground(String... params) {

        try {
            URL url = new URL(params[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            int lenghtfile = connection.getContentLength();

            BufferedInputStream input = new BufferedInputStream(url.openStream());  //
            File dir= new File(Environment.getExternalStorageDirectory().getParent());
            File myDir = new File(dir,"Downloads");
            File outFile = new File(myDir,"yE0qUN.jpg");
            outFile.mkdirs();


            byte[] myfile = new byte[lenghtfile];

            input.read(myfile);

            OutputStream output = new FileOutputStream(outFile);
            output.write(myfile);
            output.flush();
            output.close();


        return null;
    }

}

【问题讨论】:

  • 你能分享异常堆栈跟踪吗?
  • 您的帖子标题错误。你想创建一个目录和一个文件。您可以删除所有下载代码,因为它无关紧要。从检查 mkdirs() 的返回值开始,如果失败则不要继续。
  • 在启动 asynctask 之前最好注意目录。
  • 此外,您的目录路径在 Android Q 上不可用。

标签: java android


【解决方案1】:

问题是我总是在创建目录。 实际上,我并没有在目录中创建文件。 现在我创建了一个目录并为我的新文件设置了路径。 我修改了上面的代码,问题解决了:

File dir = new File((Environment.getExternalStorageDirectory() + "/"+"Downloads"));  

 dir.mkdirs();

 File outFile = new File(dir,"wallpaper.png");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2016-05-09
    • 2016-07-05
    相关资源
    最近更新 更多