繁体   English   中英

我想从网络下载图像但给出这个异常:android.system.ErrnoException:打开失败:ENOENT(没有这样的文件或目录)

[英]i want to download a image from network but give this Exception :android.system.ErrnoException: open failed: ENOENT (No such file or directory)

在此处输入图片说明 我把权限放在清单中。 我想从互联网下载图像并将其存储在外部存储中。 图片链接没问题。 写入外部存储器时出现问题。

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;
    }

}

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

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

 dir.mkdirs();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM