如何使用java编辑文本文件中的记录?

时间:2015-11-03 22:35:05

标签: java file-io text-files

我有一个文本文件,其中包含以下记录:

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();
}

1 个答案:

答案 0 :(得分:1)

经过很长一段时间,我终于找到了我的问题的解决方案:

这很简单:只需添加以下行:

y.close();

行之前:

if(checkaccount)

说明:当您尝试编辑文件时,文件仍处于打开状态。 所以它会给出错误,直到你关闭它才能进行编辑。

所以你必须在编辑之前关闭文件。