I create an I/O class to read and append some text to a file.
I supposed it has been written but for some reasons it's not shown in the file - although the program recognize it.
The file TestResult.csv
is in the src/main/resources
folder inside the program folder.
I learned how to open and read it from an tutorial on HowToDoInJava: Read a file from the ‘resources’ folder.
My Code
The first couple of code lines are pretty similar to the example in the website.
import java.io.*;
import java.nio.file.Files;
import java.io.FileWriter;
public class ReadResourceFileDemo {
public static void main(String[] args) throws IOException {
//open file
ClassLoader classLoader = IOLab.class.getClassLoader();
File file = new File(classLoader.getResource("TestResult.csv").getFile());
//append
try (FileWriter fw=new FileWriter(file, true)) {
fw.append("\nJulie,Brown,100,A");
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
}
}
}
What I got in TestResult.csv
Alex,Smith,99,A
Jolene,Schmidt,100,A
Mackinzie,Jensen,86,B
The goal is to append the String to the TestResult.csv
.
After I ran the first time the result was:
Alex,Smith,99,A
Jolene,Schmidt,100,A
Mackinzie,Jensen,86,B
Then I run again for the second time and got:
"C:\Program Files\Java\jdk-16.0.2\bin\java.exe" "-javaagent:C:\Program
Files\JetBrains\IntelliJ IDEA 2021.2.1\lib\idea_rt.jar=56365:C:\Program
Files\JetBrains\IntelliJ IDEA 2021.2.1\bin" -Dfile.encoding=UTF-8 -classpath
C:\Users\tuant\IdeaProjects\untitled\target\classes edu.sdccd.cisc191.ReadResourceFileDemo
Alex,Smith,99,A
Jolene,Schmidt,100,A
Mackinzie,Jensen,86,B
Julie,Brown,100,A
Process finished with exit code 0
Issue
This means for the first time the program skipped the append or it did but didn't show in the file for some reason.
When I open the file TestResult.csv
it only has the first 3 lines.
However, the 4th line that appended manually as
Julie,Brown,100,A
didn't show up.
Thanks a lot for any help!