Search code examples
javafilejava.util.scannerbufferedreaderbufferedwriter

How to rename a txt file using Java after copying contents from another txt file


I have created a program where there is a file called groups.txt. This file contains a list of names. To delete a group, it has to exist within the file. I used the Scanner method to search through each line for the name. If it contains the line, it sets val as 1. Which triggers the val == 1 condition. What I wanted to do during this block, is try to delete groupName from the groups.txt file. To do this, I created a new txt file called TempFile which copies all the names from groups.txt EXCEPT groupName. This file is then renamed to groups.txt and the old groups.txt file is deleted.

Everything works as intended, except the renaming. The temp.txt file still exists and the groups.txt file is unchanged. I checked the boolean success, and it always returns as false. Any ideas how to solve this?

 if (method.equals("delete group")){
                int val = 0;
                String groupName = myClient.readLine();

                try {
                    Scanner file = new Scanner(new File("groups.txt"));

                    while (file.hasNextLine()){
                        String line = file.nextLine();

                        if (line.indexOf(groupName) != -1){

                                val = 1;    
                        } 
                    }
                     if (val == 1){

                                try {

                                    File groupFile = new File("groups.txt");
                                    File tempFile = new File("temp.txt");

                                    BufferedReader reader = new BufferedReader(new FileReader(groupFile));
                                    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

                                    String currentLine;
                                    System.out.println(groupName);
                                    while ((currentLine = reader.readLine()) != null){

                                        String trimLine = currentLine.trim();

                                        if (trimLine.equals(groupName)){
                                             continue;
                                        } else {
                                            writer.write(currentLine + System.getProperty("line.separator"));
                                        }
                                    }
                                    writer.close();
                                    reader.close();
                                    groupFile.delete();
                                    boolean success = tempFile.renameTo("groups.txt");

                                } catch (IOException f){
                                    System.err.println("File Not Found: " + f.getMessage());
                                }                       }

                } catch (FileNotFoundException f){
                    System.err.println("File Not Found Exception: " + f.getMessage());
                }

            }

CODE BEFORE THE ABOVE:

 if (command.equals("group")){
            String method = myClient.readLine();

            if (method.equals("create group")){

                String groupName = myClient.readLine();

                int val = 0;

                try {
                    Scanner file = new Scanner(new File("groups.txt"));

                    while (file.hasNextLine()){
                        String line = file.nextLine();
                        if (line.indexOf(groupName) != -1){
                            Report.error("group name already exists, please pick another");
                            val = 1;                                
                        }
                    }
                } catch (FileNotFoundException f){
                    System.err.println("File Not Found: " + f.getMessage());
                }

                if (val == 0){
                    try {
                        PrintWriter out = new PrintWriter(new FileWriter("groups.txt", true));
                        out.println(groupName);
                        out.close();

                    } catch (IOException e){
                        Report.error("IOException: " + e.getMessage());
                    }
                }   

In the second part of the code, this is where I originally update the groups.txt file. So every time the user adds a group, it updates the groups.txt file by adding the new groupName to the end of the file. First, I make sure the groupName doesn't already exist using Scanner. myClient is a BufferedReader which reads from another class which stores what the user types in the command line.


Solution

  • Also do not forget to close Scanner. First you should make delete() work and make sure you know your current working directory, and write your filepath relative to it. Check with:

    File file = new File("abc.txt");
    System.out.println(file.getAbsolutePath());
    

    One thing might be unrelated, also check your environment because

    In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case. The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D: