java.io.FileNotFoundException:(访问被拒绝)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17400235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:54:36  来源:igfitidea点击:

java.io.FileNotFoundException: (Access is denied)

javafilefile-permissionsfilenotfoundexception

提问by Imesh Chandrasiri

I'm trying to create some files dynamically in my Java project root. but I get the following error when I run the code.

我正在尝试在我的 Java 项目根中动态创建一些文件。但是当我运行代码时出现以下错误。

java.io.FileNotFoundException: D:\POS_ALL\T_POS_NEWEST\TouchPosApplication\WebContent\zharaimages9 (Access is denied)

Is it possible to write a file to the root project folder in Java? Here is the code used.

是否可以在 Java 中将文件写入根项目文件夹?这是使用的代码。

private void createImage(PosItemImageDTO imageDTO,String path) throws IOException {
        byte[] bytes = imageDTO.getPosItemImage();
        path = path + "\";
        if(bytes!=null && bytes.length>0){
            OutputStream out = null;
            // BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
            File l = new  File(path);

            out = new BufferedOutputStream(new FileOutputStream(path));
            out.write(bytes);

            if (out != null) {
                out.close();
            }
        }   
    }

回答by voidMainReturn

Its because it seems like you are trying to open and read a directory here. Your file as you say it, doesn't have any extension specified so java takes it as a directory. use isFile()method to check for a file before opening. You can use listFiles()method to obtain files of the directory.

这是因为您似乎正在尝试在此处打开和读取目​​录。您所说的文件没有指定任何扩展名,因此 java 将其作为目录。isFile()在打开文件之前使用方法检查文件。您可以使用listFiles()方法来获取目录的文件。

回答by lbear

Please make sure path = path + "\\";is a correct path. If there is a directory, the program will show you Access is denied. You should add some checks before open the file, just like if (l.isDirectory()).

请确保path = path + "\\";路径正确。如果有目录,程序会显示给你Access is denied。您应该在打开文件之前添加一些检查,就像if (l.isDirectory()).