Java - 文件写入 - 访问被拒绝

时间:2021-06-09 17:35:45

标签: java file-io

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

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

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

2 个答案:

答案 0 :(得分:1)

您必须提供一段实际代码以检测方法中的问题。但是,如果您只需要一种编写简单文件的方法,请使用此方法(使用 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 !!");
}

答案 1 :(得分:0)

你需要附上你的源代码以获得更好的答案,但这里有一个工作写入文件函数的例子。

 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();
        } 
}
相关问题