[英]JAVA8, parsing text file and parsing its values to objects
我有特定的文本文件,如下所示:
name: meeting_name1
description:
04/18/2012 00:00:00
05/18/2012 00:00:00
... (more dates)
07/18/2012 00:00:00
name: meeting_name2
description: some_desc
04/18/2012 00:00:00
05/18/2012 00:00:00
... (more dates)
07/18/2012 00:00:00
(etc)
我有看起來像這樣的Java對象:
class Meeting {
String name;
String description;
List<Date> dates;
}
我的觀點是讀取文件,解析值,創建對象並將其保存到數據庫。
我可以逐行讀取文件並將其轉換為List<String>
,即。 所有數據在一起。 我可以用值創建並填充一個Java對象,然后將其保存到數據庫中。
我的問題是如何確定我在新對象開始的日期和行(名稱:meeting_name2)的結尾。
所以我可以做類似List<List<String>>
,其中List<String>
等於一個對象,即。 List<Meeting>
不知道它是否可以理解,很抱歉格式化。
假設您可以將文件數據讀取到List變量。 (請參閱上面的答案)
List<String> lines = Files.readAllLines(Paths.get("FILE_NAME"));
現在,您可以看到以下代碼作為演示。 這是一個簡單的循環,如果不是這樣的話。 希望對您有幫助。
public static void main(String[] args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
List<String> data = new ArrayList<>();
data.add("name: meeting_name1");
data.add("description: some_desc");
data.add("07/18/2012 00:00:00");
data.add("07/18/2012 00:00:00");
data.add("name: meeting_name2");
data.add("description: some_desc");
data.add("07/18/2012 00:00:00");
List<Meeting> result = new ArrayList<>();
Meeting temp = null;
for (String line : data) {
if (line.startsWith("name:")) {
temp = new Meeting(line.split(":")[1].trim());
result.add(temp);
} else if (line.startsWith("description:")) {
temp.setDescription(line.split(":")[1].trim());
} else {
temp.getDates().add(simpleDateFormat.parse(line)); // Use date for
}
}
System.out.println(result.get(0).getName() + ": " + result.get(0).getDates().size()); // meeting_name1: 2
System.out.println(result.get(1).getName() + ": " + result.get(1).getDates().size()); // meeting_name2: 1
}
static class Meeting {
String name;
String description;
List<Date> dates;
public String getName() {
return name;
}
public List<Date> getDates() {
return dates;
}
Meeting(String name) {
this.name = name;
this.dates = new ArrayList<>();
}
public void setDescription(String description) {
this.description = description;
}
}
一種可能性是首先讀取所有行。 您無需擔心以下行的結尾:
List<String> lines = Files.readAllLines(Paths.get("FILE_NAME"));
然后遍歷數組,如果一行以“ name:”開頭,則創建一個新對象並添加如下數據:
List<Meeting> meetings = new ArrayList();
Meeting currentMeeting;
for (String line : lines) {
if(line.startsWith("name:"))
{
currentMeeting = new Meeting();
meetings.add(currentMeeting);
//...add data (name)
}
//...add more data (description and dates)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.