使用文本文件更改 java 中用户帐户的密码?

change password of user account in java using text files?

我有一个问题,希望找到解决方案。

现在我已经创建了一个简单的程序来使用 java 中的文本文件更改用户帐户的密码。

现在我应该输入帐户的用户名,然后更改该帐户的密码,但它显示错误。

这是我的代码:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;
import java.util.Scanner;

public class Test6 {
public static void main(String[] args)throws IOException {

    String newPassword=null;
    boolean checked = true;

 File f= new File("C:\Users\فاطمة\Downloads\accounts.txt");// path to your file
 File tempFile = new File("C:\Users\فاطمة\Downloads\accounts2.txt"); // create a temp file in same path
 BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
 Scanner sc = new Scanner(f);
 System.out.println("Enter account username you want to edit password?");
 Scanner sc2 = new Scanner(System.in);
 String username = sc2.next();
 while(sc.hasNextLine())
 {
     String currentLine= sc.nextLine();
     String[] tokens = currentLine.split(" ");
     if(Objects.equals(Integer.valueOf(tokens[0]), username) && checked)
     {
         sc2.nextLine();                          
         System.out.println("New Password:");
         newPassword= sc2.nextLine();
         currentLine = tokens[0]+" "+newPassword;
         checked = false;
     }
     writer.write(currentLine + System.getProperty("line.separator"));

 }
 writer.close(); 
 sc.close();
 f.delete();
 boolean successful = tempFile.renameTo(f);

}
}

错误显示给我:

Exception in thread "main" java.lang.NumberFormatException: For input string: "HAMADA"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at Test6.main(Test6.java:25)

我的文本文件的格式是这样的:

HAMADA 115599
JOHNY 4477100

将第 25 行的 Integer.valueOf(tokens[0]) 更改为 tokens[0]

在您的代码中,您尝试获取用户名的整数值,而您应该获取其 String 表示形式。你不需要Integer.valueOf()。 (抛出错误是因为您试图获取非整数类型的 Integer 表示。)

附带说明一下,您永远不应该拥有存储密码的文本文件,尤其是当密码和文件都未加密时。请改用数据库。