首页 > 解决方案 > 读取文本文件中的一个字符

问题描述

我记得在 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");
    }
}

我确定以前有人问过这个问题,但我似乎找不到与该主题相关的任何内容。

标签: javafile

解决方案


据我了解,你可以做这样的事情

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();

或使用拆分方法:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String)


推荐阅读