gpt4 book ai didi

Java - 使用Scanner读取大文本文件

转载 作者:行者123 更新时间:2023-12-02 08:14:51 25 4
gpt4 key购买 nike

我有一个非常大的文本文件,其中包含客户信息。我想从文本文件中读取所有客户信息。

这就是我的文本文件的组织方式:

Costomer 1:
Name:
Erik Andersson
Adress:
Street1
Phone number:
085610540

Costomer 2:
Name:
Lars Larsson
Adress:
Street1
Phone number:
085610540

我希望能够读取所有客户信息。有什么好的办法吗?我读过有关扫描仪和图案的内容,想知道在这种情况下使用它们是否是个好主意?我的文本文件非常大,包含数百个客户。

有人知道我如何从文本文件中读取所有信息吗?我创建了一个带有客户变量的类,我只需要帮助读取文本文件。我想以有组织的方式阅读信息。

非常感谢所有帮助。

最佳答案

像这样:

public void getEmployees(File f) throws Exception {
// An ArrayList of your Employee-Object to hold multiple Employees
ArrayList<Employee> employees = new ArrayList<Employee>();
// The reader to read from your File
BufferedReader in = new BufferedReader(new FileReader(f.getAbsolutePath()));
// This will later contain one single line from your file
String line = "";

// Temporary fields for the constructor of your Employee-class
int number;
String name;
String adress;
String phone;

// Read the File untill the end is reached (when "readLine()" returns "null")
// the "line"-String contains one single line from your file.
while ( (line = in.readLine()) != null ) {
// See if your Line contains the Customers ID:
if (line.startsWith("Customer")) {
// Parse the number to an "int" because the read value
// is a String.
number = Integer.parseInt(s.substring("Customer ".length()).substring(0,s.indexOf(':')));
} else if (line.startsWith("Adress:")) {
// The Adress is noted in the next line, so we
// read the next line:
adress = in.readLine();
} else if (line.startsWith("Phone number:")) {
// Same as the Adress:
phone = in.readLine();
} else if (line.startsWith("Name:")){
// Same as the Adress:
name = in.readLine();
} else if ( line.equals("") ){
// The empty line marks the end of one set of Data
// Now we can create your Employee-Object with the
// read values:
employees.add(new Employee(number,name,adress,phone));
}
}
// After we processed the whole file, we return the Employee-Array
Employee[] emplyeeArray = (Employee[])employees.toArray();
}

请给+1并更正你的硬件哈哈

关于Java - 使用Scanner读取大文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6637459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com