java - 我想从网络下载图像,但出现以下异常:android.system.ErrnoException:打开失败:ENOENT(无此类文件或目录)-LMLPHP我在清单中放了权限。
我想从互联网下载图像并将其存储在外部存储中。
图片链接还可以。
写入外部存储器时出现问题。

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");

关于java - 我想从网络下载图像,但出现以下异常:android.system.ErrnoException:打开失败:ENOENT(无此类文件或目录),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60464812/

10-11 22:34
查看更多