我正在尝试制作一个可以从文本文件中读取用户名和密码的登录屏幕。我已经构建了注册页面,通过执行以下命令将用户名和密码输出到文件中:
try (BufferedWriter out = new BufferedWriter(fstream)) {
try {
out.write(username + " " + password);
out.newLine();
JOptionPane.showMessageDialog(null,"User Account '" + username + "' Created");
} catch (IOException ex) {
Logger.getLogger(ServerMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
文本文件将如下所示:
user1 password1
user2 password2
我一直在阅读大量文档,试图找出这个问题,但是我读得越多,就越感到困惑。我这样做的原因是为了我可以继续读取和写入 .dat 文件以获取系统最终保存的信息。
如果有人能以任何方式帮助我,那就太棒了!
谢谢
C
最佳答案
快速简单的解决方案。每行都带有注释,但如果您需要任何帮助或有任何疑问,请告知。
import java.io.*;
class FileRead
{
public static boolean main(String lineToCompare)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Compare the line with the line to compare (string)
if(strLine.compareTo(lineToCompare) == 0)
return true;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return false;
}
}
关于java - 在文本文档中搜索一行 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10200909/