javaeclipsefilebufferedwriter

A file in my resources folder isn't getting written with try-with-resources and BufferedWriter, why?


I have a file test.txt in the resources folder of my project, and I'm trying to write a List of strings to it, one for each line (from a test class, if it matters).
For some reason, despite no exception being thrown or caught, I've tried many things but I'm not being able to write to it. For example:

Path p = Paths.get(ClassLoader.getSystemResource("test.txt").toURI());

try (BufferedWriter writer = Files.newBufferedWriter(p)) 
{
    for (String line : lines) writer.write(line);
} 
            
catch (IOException e) 
{
    e.printStackTrace();
}

Files.write(p, lines) does not work either. I'm perplexed because no error is reported but the file remains empty. I also made sure the path is recognized with p.toFile().exists(), and it does return true . What am I missing?


Solution

  • I assume you are running this from your IDE?

    The IDE will build the project and copy the resources along with the compiled .class files to an output directory. When modifying any of these resources, the copied resource files will be overwritten, but not the source resource files - I assume you're looking at these now and see that they still look the same. Moreover the copied resource files might get overwritten every time you build the project.

    Hint: output (print) the path to check which file you're actually modifying.