Java - file writing - access denied

32
June 10, 2021, at 12:20 PM

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();
Answer 1

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 !!");
}
Answer 2

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();
        } 
}
READ ALSO
Plyr Speed Opens from Above - Want it to open from below

Plyr Speed Opens from Above - Want it to open from below

So, I have this website where there's audio and the player is Plyr (https://githubcom/sampotts/plyr)

50
NodeJs - how to populate the model view with data from another model

NodeJs - how to populate the model view with data from another model

I am practicing Node by making a simple inventory app, in which I have 3 models: Item, Category and ManufacturerWhat I want to do is, when displaying an item details, to include the Category and Manufacturer associated with that specific item, however...

29
Date of Birth does not show and Form cannot edit in PHP

Date of Birth does not show and Form cannot edit in PHP

I will describe my problems brieflyThere are 2 main issues in my web app:

12
AWS Lambda: Input values needs to be concatenated with error message

AWS Lambda: Input values needs to be concatenated with error message

The query returns the expected result, the request in this forum is regarding the customized error messageIncase of failure the exception needs to stored along with the input values

50