简体   繁体   English

使用 Java 从文件中读取混合类型的数据

[英]Read mixed types of data from a file with Java

I am a bit stuck with this code.我对这段代码有点困惑。 I have file file name.txt which contains following data:我有包含以下数据的文件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

I can't read first and last name of user in the same string.我无法在同一个字符串中读取用户的名字和姓氏。 Here is my code:这是我的代码:

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

Consider using different data layout in the file.考虑在文件中使用不同的数据布局。 It's easier if you have all the required data in a single line, eg comma separated especially if you have information about multiple users (and I guess that's the case)如果您在一行中包含所有必需的数据,则更容易,例如逗号分隔,特别是如果您有关于多个用户的信息(我想就是这种情况)

FS1, FirstName, LastName, foo@bar.baz, 10.0, 100

Then you can go with something like this然后你可以使用这样的东西

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];
}

Or you can use Java 8 to simplify this to:或者您可以使用 Java 8 将其简化为:

new Scanner(new File("customer.txt"))
    .forEachRemaining(line -> {
             String[] splitted = line.split(", ");
             // etc. 
    });

or to:或者:

Files.lines(Paths.get("customer.txt"))
         .forEach(line -> {
             String[] splitted = line.split(", ");
             // splitted[0] = user Id
             // splitted[1] = user name and surname
             // etc. 
         });

Also, a friendly advice, make yourself acquainted with Java's naming conventions it'd make your code much cleaner and easier to read.另外,一个友好的建议,让你自己熟悉 Java 的命名约定,它会让你的代码更清晰,更容易阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM