简体   繁体   中英

Renaming file to existing file java

I am trying to

  1. Create Temp File "Temp Account Info.txt"
  2. Write information from existing Account File "Account Information.txt" TO "Temp Account Info.txt"
  3. Omit certain information
  4. Delete "Account Information.txt"
  5. Rename "Temp Account Info.txt" to "Account Information.txt"

My issue is steps 4 and 5. Nor am I sure if I am ordering it correctly. The code is provided below.

public static void deleteAccount(String accountNumber) throws Exception {
    File accountFile = new File("Account Information.txt");
    File tempFile = new File("Temp Account Info.txt");
    BufferedReader br = new BufferedReader(new FileReader(accountFile));
    FileWriter tempFw = new FileWriter(tempFile, true);
    PrintWriter tempPw = new PrintWriter(tempFw);

    String line;
    try {
        while ((line = br.readLine()) != null) {
            if(!line.contains(accountNumber)) {                    
                tempPw.print(line);
                tempPw.print("\r\n");
            }
        }
        **FileWriter fw = new FileWriter(accountFile);
        PrintWriter pw = new PrintWriter(fw);
        tempFile.renameTo(accountFile);
        accountFile.delete();
        fw.close();
        pw.close();
        tempFw.close();
        tempPw.close();
    } catch (Exception e) {
        System.out.println("ERROR: Account Not Found!");
    }
}

The full code can be found at: https://hastebin.com/eposapecep.java

Any help would be greatly appreciated!

I am aware that I do not correctly check for "Account Not Found" and will try to figure this out after the naming issue.

Thanks in advance!

Use the renameTo() method of File.

   try {
        File file = new File("info.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));

        String str = br.readLine();

        File file2 = new File("temp.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(file2));

        bw.write(str);

        br.close();
        bw.close();
        if (!file.delete()) {
            System.out.println("delete failed");
        }
        if (!file2.renameTo(file)) {
            System.out.println("rename failed");
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

The code above reads the first line of info.txt, writes it to temp.txt, deletes info.txt, renames temp.txt to info.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM