我正在制作一个程序,要求您输入密码,并添加一个稍后更改密码的选项,但是每次我关闭它并再次打开它时,每次打开时密码都会重置为默认值再来一次。我已将默认关闭操作设置为隐藏,但我认为每次再次运行该程序时,它都是全新的。另外,我查看了任务管理器的后台程序,发现有很多“Java TM Platform SE Binary”。 这是我的核心问题:
当我从 eclipse 运行一个程序时,它每次都会打开一个全新的程序吗?我可以改变这个吗?
如何在程序中的打开/关闭操作中保存变量?
提前致谢
最佳答案
您没有发布任何代码,因此我假设您定义了一个 password
变量,并且您的程序如下所示:
Scanner userInput = new Scanner(System.in);
String password = "Default01";
System.out.print("Enter new password: ");
password = userInput.next();
每次运行程序时,它都会在 RAM 中创建一个全新的password
变量实例。当程序关闭时,RAM 中的所有内容都会被破坏。您需要某种持久存储来将信息写入变量。文本文件是一种简单的开始方式。添加它将使您的程序看起来像:
Scanner userInput = new Scanner(System.in);
File passwordFile = new File("passwordfile.txt");
//this is where the password is stored.
Scanner passwordScanner = new Scanner(passwordFile);
//this is how you read the file.
String password = passwordScanner.next();
//password has been read.
...然后提示输入新密码。
System.out.print("Enter new password: ");
password = userInput.next(); //prompt for new password
...然后将该新密码写入文件以进行持久存储。
PrintWriter passwordWriter = new PrintWriter("passwordfile.txt");
// overwrites the current passwordfile.txt, so you now have an empty file
passwordWriter.print(password);
//writes the password to passwordfile.txt so it can be used next time.
希望对您有所帮助!
关于java - 关闭jframe并在java中重新打开后保存变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20248051/