0

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

ASD1122
  • 1
  • 2
  • Your code doesn't show any call to `Files`. That's a crucial part of your problem and should be included in the post. "i also use ... thread implement it still don't work." That could make the situation worse. – erickson Sep 27 '22 at 14:30
  • @erickson Thank you very much for your reply. I update Files method that I use I try to copy/rename/move/delete also with and with out option and nothing work. is this what you ask for? if not please let me know I am very new to programming (and also any suggestions are very appreciated) – ASD1122 Sep 27 '22 at 14:55
  • Sort of. You should start with an [mcve] that reproduces the problem on your system and post that. With the various stories you've told, I am not confident what thread `update_user_data()` is called, or when. – erickson Sep 27 '22 at 15:02
  • Are you reading from the same file you are trying to write to? – vsfDawg Sep 27 '22 at 15:07
  • '''update_user_data()''' is call when button is press using JavaFX (fxml). basically I try to change any data on CSV file. this method should consume what column name to edit and new data so this method can edit CSV files. right now everything works except the last one that should move the temporary file to original file(delete original and change temporary file to original name) but it get this "The process cannot access the file because it is being used by another process" error – ASD1122 Sep 27 '22 at 15:13
  • @vsfDawg i read the original file get that data and write a temporary file with data that I read and update it with data I want to update(new_data parameter). (all above it work ) when it finish. I want to delete original file and rename temporary to be a new original file. this part is what I get error. – ASD1122 Sep 27 '22 at 15:15
  • The question includes the code that reads the original file and writes to a temporary file. In the previous comment you state that this works. When you go to delete the original file and/or when you rename the temp file is when you get an exception? Please add THAT code to the question if that is the case and include the full stacktrace. – vsfDawg Sep 27 '22 at 15:22
  • @vsfDawg I update it in question sorry for forget it. by the way this is all error I got 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 and java 17 – ASD1122 Sep 27 '22 at 15:32

1 Answers1

0

The code contains only one serious bug, continue causes the replacement of all lines after Userprofile.getUserline().

And String objects are immutable. So you need to do s = s.trim() as trim() delivers a new String value not altering the original string.

Furthermore I used Files with its utility functions.

protected static void editCsvData(String columname, String newData) throws IOException {
    Path accountPath = accountfile.toPath();
    // When File. Or when String: Paths.get(accountfile).
    Path tempPath = tempFile.toPath();
    try (BufferedReader reader = Files.newBufferedReader(accountPath,
                                     Charset.defaultCharset());
            BuffedWriter writer = Files.newBufferedWriter(tempPath,
                                      Charset.defaultCharset())) {

        String currentLine;
        int index = 10;
        int line = 0;
        while ((currentLine = reader.readLine()) != null) {
            if (line == Userprofile.getUserline()) {
                currentine = currentLine.trim();
                String[] data = currentLine.split(",");
                for (int x = 0; x < data.length; x++) {
                    if (x > 0) {
                        writer.write(",");
                    }
                    writer.write(index == x ? newData : data[x]);
                }
            } else {
                writer.write(currentLine);
            }
            writer.write(System.getProperty("line.separator"));
            ++line;
        }
        System.err.println("write fin");
    }
}

What concerns the error: there are two files here: accountFile and tempFile. Either one could not have been closed - kept in use - and cause the mentioned error.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Note that somewhere else the file must still be opened. Like the tempFile reused (same name). – Joop Eggen Sep 27 '22 at 16:54
  • Note that somewhere else the file must still be opened. Like the tempFile reused (same name). in this case may I use reader.close(); or other method to close file ? or may be I should try with different approach – ASD1122 Sep 27 '22 at 16:58