【问题标题】:Java - file writing - access deniedJava - 文件写入 - 访问被拒绝
【发布时间】:2021-06-09 17:35:45
【问题描述】:

我正在尝试从我的 Java 应用程序中写入一个文件,但除了在 app 目录中之外,我无法将它写入任何地方。我使用的是 Windows 10。我尝试以管理员身份启动 Eclipse,并尝试使用 Launch4j 打包可运行的 Jar 文件,得到了同样的错误。 任何想法如何将文件写入用户定义的目录?

我正在使用 PdfWriter 包,它是用 Java FileOutputStream 实例化的:

Document document = new Document();      
var writer = PdfWriter.getInstance(document, new FileOutputStream(directory));
                document.open();

【问题讨论】:

  • 欢迎来到 Stack Overflow。请花点时间阅读How to Ask。然后edit您的问题以遵循那里提出的建议,包括创建minimal reproducible example。尽可能简单。例如,从硬编码的目录字符串开始。然后,当您进行该工作时,请改用变量。然后从那里去。

标签: java file-io


【解决方案1】:

您必须提供实际代码的 sn-p 以检测方法中的问题。但是,如果您只需要一种编写简单文件的方法,请使用此方法(使用 java 8)

//Get the file reference
Path path = Paths.get("c:/output.txt");
 
//Use try-with-resource to get auto-closeable writer instance
try (BufferedWriter writer = Files.newBufferedWriter(path)) 
{
    writer.write("Hello World !!");
}

【讨论】:

    【解决方案2】:

    您需要附上您的源代码以获得更好的答案,但这里是一个工作写入文件功能的示例。

     void writeToFile(String input) throws IOException{
                File file = new File("C:\\YourDirectory\\FileName.txt");
                if (!file.getParentFile().mkdirs())
                        throw new IOException("Unable to create " + file.getParentFile());
                BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
                try{
                        out.append(input);
                        out.newLine();
                } finally {
                
    
        out.close();
            } 
    }
    

    【讨论】:

    • 好的我解决了这个问题,只是一个小细节我没有考虑。
    • @Maxim 使用该详细信息更新您的问题,以帮助其他人在未来遇到同样的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 2014-02-28
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多