简体   繁体   中英

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?

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.

if you are using maven, files inside src/main/resources will be copied to output folder target/classes/test.txt. Print your file path and see the actual path that your are using.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM