Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...