java - 下载图像时 FileOutputStream 崩溃并出现 "open failed: EISDIR (Is a directory)"错误

标签 java fileoutputstream

我正在尝试从互联网上下载一个 iamge,这是代码:

try {
                String imgURL = c.imgURL;
                String imgPATH = c.imgPATH;
                URL url = new URL(imgURL);
                URLConnection conexion = url.openConnection();
                conexion.connect();
                int lenghtOfFile = conexion.getContentLength();
                try {
                    File f = new File(imgPATH);
                    f.mkdirs();

                    BufferedInputStream input = new BufferedInputStream(url.openStream());
                    BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(imgPATH), 8192); // CRASH HERE

                    byte data[] = new byte[8192];
                    long total = 0;
                    int count = 0;
                    int updateUILimiter = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;

                        if (updateUILimiter == 20)
                            // publishProgress((int) (total * 100 / lenghtOfFile));
                            updateUILimiter = 0;
                        else
                            updateUILimiter++;

                        output.write(data, 0, count);

                        if (isCancelled()) {
                            output.flush();
                            output.close();
                            input.close();
                            return null;
                        }

                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {
                    c.imgPATH = "";
                    return null;
                }


            } catch (Exception e) {
                c.imgPATH = "";
                return null;
            }

这里是错误信息:

/mnt/sdcard/tmp/3.png: open failed: EISDIR (Is a directory)

这是为什么?

“/mnt/sdcard/tmp/”存在。

最佳答案

3.png 是一个目录,因为你通过调用 f.mkdirs(); 来实现它。尝试 f.getParentFile().mkdirs() 代替。来自 documentation :

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

(强调我的)。换句话说,包含在 File 实例 f 中的整个路径被视为目录名称,直到并包括最后一部分(3.png 在示例输出中)。

关于java - 下载图像时 FileOutputStream 崩溃并出现 "open failed: EISDIR (Is a directory)"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12339673/

相关文章:

android - 写入外部存储文件notfoundexception

java - 有没有办法在java swing中显示没有JLabel或JTextField的文本?

java - 基于异步队列的文件写入

java - Java 中的数组?

Java 向文件写入字节和从文件读取字节

java - 复制现有的 png 文件并以编程方式重命名

java - 如何重新创建仅修改文件名的链接 OutputStream

java - 将字节数组写入java中的子文件夹

java - 将现有 Java 项目放入 Github

java - Elasticsearch GetResponse.getField 抛出 NullPointerException