Hi i try to implement csv edit method using https://stackoverflow.com/a/1377322 as example. everything work except when i try to Files.copy/move/delete it i get this "The process cannot access the file because it is being used by another process" error. i also use (try with resource) and thread implement it still don't work. this error is only base on bufferreader file so may i ask what seem to be the problem.
protected static void edit_csv_data(String columname, String new_data) throws IOException {
try (FileReader fr = new FileReader(accountfile); BufferedReader reader = new BufferedReader(fr)) {
File tempFile = new File(tempfile);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
int index = 10;
int line = 0;
while ((currentLine = reader.readLine()) != null) {
if (line == Userprofile.getUserline()) {
currentLine.trim();
String[] data = currentLine.split(",");
for (int x = 0; x < data.length; x++) {
if (index == x) {
writer.write(new_data);
} else writer.write(data[x]);
if (x < data.length - 1) writer.write(",");
}
writer.write(System.getProperty("line.separator"));
continue;
}else {
writer.write(currentLine + System.getProperty("line.separator"));
}
line += 1;
}
writer.flush();
writer.close();
reader.close();
System.err.println("write fin");
return;
}
I also try resource monitor in window 11 .the process java.exe and I also cant delete file when java is running or even after error was thrown and I can edit accountfile after close java or leave program open long enough i can delete file even java is run so i believe BufferReader is Stuck and not close properly.
CSV File '''
Username,Password,Account_Type,Name,Surname,ID,Email,Picture_name,Ban_status,Attemp_Login_during_Baned,Last_Login
admin,1234,admin,Chicken,Little,62001,ASD.l@hotmail.com,picture.jpg,false,0,132
'''
protected static void update_user_data(String columname, String new_data) throws IOException {
DataEdit.edit_csv_data(columname,new_data);
System.err.println(Files.isWritable(Path.of(accountfile)));
Files.copy(Path.of(tempfile), Path.of(accountfile_back),StandardCopyOption.REPLACE_EXISTING);
Files.copy(Path.of(accountfile), Path.of(accountfile_back), StandardCopyOption.REPLACE_EXISTING);
Files.copy(Path.of(tempfile), Path.of(accountfile),StandardCopyOption.REPLACE_EXISTING);
return;
}
Error
java.nio.file.FileSystemException: src\main\java\allaccount\data\Account.csv: The process cannot access the file because it is being used by another process
FYI I use Intellij IDE,maven for build,java 17