user3568791
user3568791

Reputation: 716

Write to resource file java?

I'm trying to dynamically write data to a resource file in java but I can't seem to succeed. Is it possible at all? I tried a few approaches but none of them worked.

I have a main method which represents:

public static void main(String[] args) throws Exception {

    ClassLoader loader = ClassLoader.getSystemClassLoader();
    File file = new File(loader.getResource("authors/authors.log").getFile());

    FileWriter writer = new FileWriter(file);
    System.out.println(file.getAbsolutePath());

    writer.write("Test test \n");

    writer.flush();

    System.out.println(file.getAbsolutePath());

    writer.write("Test 2");

    writer.flush();
    writer.close();

}

After executing the main method an exception isn't thrown but the authors.log file doesn't seem to be changed and no data is written.

Files are :

src/main/java/main/Main.java

src/main/resource/authors/authors.log

target/classes/authors/authors.log

However the target directory contains an authors.log file and all the data is written there. Am I wrong somewhere or just java doesn't allow writing to a resource file ? If so where is the best place to store files which are changed by the program (e.g. log files)

Upvotes: 0

Views: 3112

Answers (1)

davidxxx
davidxxx

Reputation: 131346

However the target directory contains an authors.log file and all the data is written there.

It is rather expected as it is the file that you opened and modified.

The following statement uses the classloader to retrieve the file and not the filesystem :

File file = new File(loader.getResource("authors/authors.log").getFile());

So it will retrieve the file located in target/classes and not which one located in src/main/resources.

Use the filesystem by specifying the relative path of the current working directory to be able to change the content of src/main/resources :

For example :

File file = new File("src/main/resources/authors/authors.log");

or better with the java.nio API :

Path file = Paths.get("src/main/resources/authors/authors.log");

If so where is the best place to store files which are changed by the program (e.g. log files)

Beyond the technical question, you should wonder why your application needs to modify the source code. It should be done only in very specific corner cases.
For example, the log files don't have to be located in the source code, these have to be outside the source code project because these don't make part of the application source code and are not tools to build the application either.

Upvotes: 3

Related Questions