java - 读取文本文件中的一个字符
问题描述
我记得在 Python 中做了一些相同的事情并发现它很容易,但我似乎无法在 Java 中找到解决方案。我基本上需要编写程序来读取文本文件,但只需要每行的第一部分。
文本文件目前看起来像
测试1,测试1 测试2,测试2 测试
3
,测试3
我有一个验证系统,所以当用户注册时,它会检查用户名尚未被使用。我只需要能够在没有密码的情况下检查用户名,或者换句话说,读取逗号之前的行。我已经有了检查登录用户名和密码的代码,如下所示
String user = userText.getText();
String pString = String.valueOf(passwordText.getPassword());
File file = new File("C:/Users/Will/Desktop/UnPs.txt");
boolean found = false;
Scanner scan = null;
try {
scan = new Scanner(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(scan.hasNextLine() && found == false) {
String passCheck = scan.nextLine();
if(passCheck.equals(user + "," + pString)) {
System.out.println("Found");
found = true;
}
else if(!passCheck.equals(user + "," + pString)) {
System.out.println("not found");
}
}
我确定以前有人问过这个问题,但我似乎找不到与该主题相关的任何内容。
解决方案
据我了解,你可以做这样的事情
Scanner read = new Scanner (new File("C:/Users/Will/Desktop/UnPs.txt"));
read.useDelimiter(",");
String name, pwd;
while(read.hasNext())
{
name = read.next();
pwd= read.next();
System.out.println(name+ " " + pwd + "\n"); //just for debugging
}
read.close();
推荐阅读
- python - Marshmallow:如何将字典或对象序列化为 XML?
- javascript - 在 javascript 中访问 JSON 并在控制台中打印它
- sql - 如何选择列等于另一列的另一种类型的值
- python - 在 pyplot.table 中插入图像/对象
- bootstrap-4 - 什么 Quasar 可以做 Bootstarp+Vuejs 做不到的?
- java - ImageView 不显示图像 - JavaFX
- vba - 刷新搜索结果
- google-chrome-arc - ARC 目前模拟什么版本的 Android?
- android - 如何修复“启动完成不是通过电话调用而是在模拟器上工作”
- typeorm - TypeORM:如何在 queryRunner 中运行 SELECT... FOR UPDATE?