使用Java从文件中读取混合类型的数据
我有点被这个代码卡住了。我有一个文件使用Java从文件中读取混合类型的数据,java,file,input,Java,File,Input,我有点被这个代码卡住了。我有一个文件file name.txt,其中包含以下数据: BD1 // user ID Bob Dillon // user full name user@email.com // user Email 10.0 // amount of cash 100 // No.of Points 我无法读取同一字符串中的用户名和姓氏。这是我的密码: Scanner input
file name.txt
,其中包含以下数据:
BD1 // user ID
Bob Dillon // user full name
user@email.com // user Email
10.0 // amount of cash
100 // No.of Points
我无法读取同一字符串中的用户名和姓氏。这是我的密码:
Scanner input_File = new Scanner(new File("customer.txt"));
int num_Customers = 0;
while(input_File.hasNext() && num_Customers < maxLoyalty_CardsQty)
{
//read ID
customerID[num_Customers] = input_File.next();
input_File.nextLine();
//Here is my problems begins
while(input_File.hasNextLine())
{
String line = input_File.nextLine();
Scanner line_Scan = new Scanner(line);
line_Scan.useDelimiter(" ");
fName[num_Customers] = input_File.next();
lName[num_Customers] = input_File.next();
line_Scan.close();
}
//read Email
email[num_Customers] = input_File.next();
//read Cash
spendToDate[num_Customers] = input_File.nextDouble();
//read Points
points[num_Customers] = input_File.nextInt();
num_Customers++;
}
input_File.close();
Scanner input_File=新扫描仪(新文件(“customer.txt”);
int num_客户=0;
while(input_File.hasNext()&&num_Customers
考虑在文件中使用不同的数据布局。如果您在一行中有所有必需的数据,例如逗号分隔的数据,则会更容易,尤其是如果您有多个用户的信息(我想情况就是这样)
然后你可以做这样的事情
Scanner scanner = new Scanner(new File("customer.txt"));
while (scanner.hasNext()) {
String[] splitted = scanner.nextLine().split(", ");
// then you've data in a nice array arranged like below
// splitted[0] = user Id
// splitted[1] = first name
// etc.
fName[numCustomers] = splitted[1];
// ...
spendToDate[numCustomers] = splitted[3];
}
或者,您可以使用Java 8将其简化为:
new Scanner(new File("customer.txt"))
.forEachRemaining(line -> {
String[] splitted = line.split(", ");
// etc.
});
或:
Files.lines(Paths.get("customer.txt"))
.forEach(line -> {
String[] splitted = line.split(", ");
// splitted[0] = user Id
// splitted[1] = user name and surname
// etc.
});
另外,一个友好的建议是,让自己熟悉Java,这将使您的代码更清晰、更易于阅读。您正在使用3种不同的方法来编写变量名。带空格的是最错误的。您是否考虑过使用定义的文件格式,如Json?你可以很容易地将它解析成一个对象,比如Gson。谢谢Kitke的代码,是的,这是实现它的方法之一,但我需要保持文件格式不变。这是我学校项目的要求之一
Files.lines(Paths.get("customer.txt"))
.forEach(line -> {
String[] splitted = line.split(", ");
// splitted[0] = user Id
// splitted[1] = user name and surname
// etc.
});