所以我试图编写一个java应用程序,其中我有一个包含一些数据的文本文件,例如:id,username,password,每条记录都在新行上。我试图实现的目标是,例如,如果用户输入" vick"我希望能够在文本文件中搜索具有" vick"的用户名。在其中并返回id,用户名,密码。
这是我到目前为止所做的:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;
public class tests {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\Vick\\PT\\Tests\\src\\users.txt");
String[] UserToken = null;
BufferedReader br = new BufferedReader(new FileReader(file));
int lineCount = 0;
while(br.readLine() != null)
{
lineCount++;
}
br.close();
Scanner inputeFile = new Scanner(file);
int uid = 0;
String username = null;
String password = null;
while(inputeFile.hasNext())
{
String str = inputeFile.nextLine();
UserToken = str.split(",");
uid = Integer.parseInt(UserToken[0]);
username = UserToken[1];
password = UserToken[2];
//Users u1 = new Users(uid, username, password);
//System.out.println(UserToken[0] + " - " + UserToken[1] + " - " + UserToken[2]);
}
Users u1 = new Users(uid, username, password);
Scanner search = new Scanner(System.in);
System.out.println("Search for user: ");
String searchterm = search.next();
while(inputeFile.hasNext())
{
if(u1.getUsername().contains(searchterm))
{
System.out.println("HE!");
}
}
}
}
这是我尝试使用的用户类
public class Users {
public int userid;
public static String username;
public String password;
public Users(int userid, String username, String password)
{
userid = userid;
username = username;
password = password;
}
public int getUID()
{
return userid;
}
public static String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
}
答案 0 :(得分:0)
- 正如此线程中有人已经说过的那样,使用hasNextLine() - 您的代码效率不高。 (首先,你遍历所有行只是为了得到计数,然后再循环它们来阅读)。我的代码也可以改进,但我会将其作为练习。 - 我测试过的示例文件
1,test,lol
2,robot,small
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Tests {
public static void main(String[] args) throws IOException {
Scanner search = new Scanner(System.in);
System.out.println("Search for user: ");
String searchterm = search.next();
File file = new File("/tmp/users.txt");
String[] UserToken = null;
BufferedReader br = new BufferedReader(new FileReader(file));
Scanner inputeFile = new Scanner(file);
int uid = 0;
String username = null;
String password = null;
while(inputeFile.hasNext())
{
String str = inputeFile.nextLine();
UserToken = str.split(",");
uid = Integer.parseInt(UserToken[0]);
username = UserToken[1];
password = UserToken[2];
// make user object here if you want to
if (username.contains(searchterm))
{
System.out.println(str);
}
}
}
}