簡體   English   中英

如何使用Java編輯文本文件中的記錄?

[英]How to edit record in a text file using java?

我有一個文本文件,其中包含以下記錄:

JOHNY 412563
SARAH 147852369

這些記錄定義用戶帳戶的用戶名和密碼。

我編寫了一種簡單的方法來編輯記錄的密碼。

編輯密碼的方法是發送要編輯的用戶名和新密碼,然后該方法應制作該密碼的版本。 但是什么也沒發生,它會將新數據復制到臨時文件中,但不會再次復制到主文件中。

這是我寫的方法:

public int change_pass(String username, String password) {

 boolean checked = true;

 try {
     File f = new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt");
     File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt");
     BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

     Scanner sc = new Scanner(f);
     Scanner sc2 = new Scanner(System.in);

     while(sc.hasNextLine()) {
         String currentLine = sc.nextLine();
         String[] tokens = currentLine.split(" ");
         if(Objects.equals(tokens[0], username) && checked) {
             currentLine = tokens[0]+" "+password;
             checked = false;
         }
         writer.write(currentLine + System.getProperty("line.separator"));
    }
    writer.close(); 
    sc.close();
    f.delete();
    boolean successful = tempFile.renameTo(f);
    if(successful == true) {
       return 1;
    } catch(Exception e) {
       e.printStackTrace();
    }
  return 0;
}

這是我寫的主要程序:

Scanner sc = new Scanner(System.in);
String newpass = null;
System.out.println("Change account password !!");
System.out.println("Validate your account please !!");
System.out.printf("Username: ");
a1.setUsername(sc.next().toUpperCase());
System.out.printf("Old Password: ");
a1.setPassword(sc.next());

Scanner y = null;
try{
    y = new Scanner(new File("C:\\Users\\?????\\Downloads\\accounts.txt"));
    boolean checkaccount = false;
    while(y.hasNext()) {
        String a = y.next();
        String b = y.next();
        if((a == null ? a1.getUsername() == null : a.equals(a1.getUsername())) && (b == null ? a1.getPassword() == null : b.equals(a1.getPassword())))
            checkaccount = true;
    }
    if(checkaccount) {
        System.out.println("Your account has been verified successfully.");
    } else
        System.out.println("Wrong username or password ... try again.");

    System.out.printf("New Password: ");
    newpass = sc.next();
    if(newpass.length() >= 6)  {
        if(c1.change_pass(a1.getUsername(), newpass) == 1)
            System.out.println("Password has been changed successfully.");
        else
            System.out.println("Error occurred during changing password, try again.");
    } else
        System.out.println("Short password: password must be at least 6 characters.");
} catch(Exception e) {
    e.printStackTrace();
}

經過很長一段時間,我終於找到了我的問題的解決方案:

非常簡單:只需添加以下行:

y.close();

前行:

if(checkaccount)

解釋:嘗試編輯文件時文件仍處於打開狀態。 因此,它會產生錯誤,並且必須先關閉它才能進行編輯。

因此,您必須在編輯之前關閉文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM