Maxim
Maxim

Reputation: 597

Java - file writing - access denied

I'm trying to write a file from my Java application but I can't write it anywhere but inside the app directory. I'm using Windows 10. I tried starting Eclipse as admin and tried packaging the runnable Jar file using Launch4j, getting the same error. Any ideas how to write a file to a user-defined directory?

I'm using the PdfWriter package, which is instantiated with a Java FileOutputStream:

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

Upvotes: 0

Views: 747

Answers (2)

Nisar Fakiri
Nisar Fakiri

Reputation: 3

You need to attach your source code for a better answer, but here is an example of working write to file function.

 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();
        } 
}

Upvotes: 0

You must provide a snippet of your actual code to detect the problem in your approach. But if you only need a way to write a simple file take this (with 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 !!");
}

Upvotes: 1

Related Questions