我遇到了问题,希望找到解决方案。
现在我创建了一个简单的程序来使用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
答案 0 :(得分:2)
将第25行的Integer.valueOf(tokens[0])
更改为tokens[0]
。
在您的代码中,当您应该获取其String
表示时,尝试获取用户名的整数值。您不需要Integer.valueOf()
。 (抛出错误是因为您尝试获取非整数类型的Integer
表示。)
另外,您应该永远不会有密码存储文本文件,尤其是当密码和文件都未加密时。改为使用数据库。