2 回答
TA贡献1821条经验 获得超4个赞
从 while 循环中删除行分隔符。
String fileName = "D:\\Files\\a.txt";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line.trim());
}
reader.close();
String content = stringBuilder.toString();
String[] dataList = content.split(",");
ArrayList<Car> carArray = new ArrayList();
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 3) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
TA贡献1850条经验 获得超11个赞
在 StringBuilder 中,您收集所有行:
AG53DBO,Mercedes,1000,(255:0:0),4\r\nMD17WBW,Volkswagen,2300,(0:0:255),5\r\n...
这个字符串应该首先被吐上ls- 然后你会有用逗号分隔的字段的行。
现在只需用逗号分割就会导致数组元素加倍4\r\nMD17WBW。
就像是:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path); // Without line ending.
List<Car> cars = new ArrayList<>();
for (String line : lines) {
String[] data = line.split(",");
Car car = new Car(data);
cars.add(car);
}
Path、Paths 尤其是Files是非常方便的类。使用 java Streams 还可以缩写如下:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<Car> cars = Files.lines(path) // Stream<String>
.map(line -> line.split(",")) // Stream<String[]>
.map(Car::new) // Stream<Car>
.collect(Collectors.toList()); // List<Car>
这里
.lines
返回Stream<String>
文件中的行(游标),没有行分隔符。然后
.map(l -> l.split(","))
分割每一行。然后在
Car(String[])
字符串数组上调用构造函数。然后将结果收集在一个列表中。
添加回答
举报