[英]Java program for reading a text file and creating objects
我目前正在編寫一個程序,以從文本文件中讀取數據並以某種方式利用數據。 到目前為止,我可以讀取文件沒有問題,但是接下來的問題是我遇到的問題。 從文本文件中讀取數據時,必須從我已經構建的類中創建適當的對象,並根據數據將其存儲在2個數組中。 就像我之前說過的那樣,我已經完成了要讀取的數據的代碼,但是我不知道如何使用該數據來創建對象並將這些對象存儲到數組中。
這是到目前為止我在main方法中擁有的代碼:
public static void main(String[] args) {
BufferedReader inputStream = null;
String fileLine;
try {
inputStream = new BufferedReader(new FileReader("EmployeeData.txt"));
System.out.println("Employee Data:");
// Read one Line using BufferedReader
while ((fileLine = inputStream.readLine()) != null) {
System.out.println(fileLine);
}//end while
} catch (IOException io) {
System.out.println("File IO exception" + io.getMessage());
}finally {
// Need another catch for closing
// the streams
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException io) {
System.out.println("Issue closing the Files" + io.getMessage());
}//end catch
}//end finally
}//end main method
您必須考慮數據如何在文本文件中表示,並將它們相應地映射到Employee
類。
以Employee
類如下所示為例-
class Employee {
String firstName;
String lastName;
}
文件中的行就像-
first1 last1
first2 last2
您可以創建Employee
的arrayList
來保存數據-
List<Employee> employees = new ArrayList();
從文件中讀取每一行時,您可以按行將行分開,構造對象並添加到列表中-
String[] name = fileLine.split(" ");
Employee e = new Employee();
e.firstName = name[0];
e.lastName = name[1];
employees.add(e);
因此,基本上,您必須考慮源(文本文件)中數據的結構,並弄清楚如何解析它們並構造所需的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.