-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatasetReader.java
More file actions
80 lines (66 loc) · 2.61 KB
/
DatasetReader.java
File metadata and controls
80 lines (66 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DatasetReader {
public static List<Book> readBooksFromCSV(String fileName) {
List<Book> books = new ArrayList<>();
String line;
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
br.readLine();
while ((line = br.readLine()) != null) {
try {
Book book = parseBookFromLine(line);
if (book != null) {
books.add(book);
}
} catch (Exception e) {
System.err.println("Error parsing line: " + line);
System.err.println("Error message: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return books;
}
private static Book parseBookFromLine(String line) {
List<String> fields = parseCSVLine(line);
if (fields.size() < 7) {
System.err.println("Incomplete data in line: " + line);
return null;
}
try {
String title = fields.get(0).trim();
String author = fields.get(1).trim();
double userRating = Double.parseDouble(fields.get(2).trim());
int reviews = Integer.parseInt(fields.get(3).trim());
double price = Double.parseDouble(fields.get(4).trim());
int year = Integer.parseInt(fields.get(5).trim());
String genre = fields.get(6).trim();
return new Book(title, author, userRating, reviews, price, year, genre);
} catch (NumberFormatException e) {
System.err.println("Error parsing numbers in line: " + line);
return null;
}
}
private static List<String> parseCSVLine(String line) {
List<String> fields = new ArrayList<>();
boolean inQuotes = false;
StringBuilder field = new StringBuilder();
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '"') {
inQuotes = !inQuotes;
} else if (c == ',' && !inQuotes) {
fields.add(field.toString());
field = new StringBuilder();
} else {
field.append(c);
}
}
fields.add(field.toString());
return fields;
}
}