java从中获取数据。csv文件转换为数组对象列表
以下是表格的格式。我正在使用的csv文件-
Hostname,IP Address,Patched?,OS Version,Notes
A.example.COM,1.1.1.1,NO,11,Faulty fans
b.example.com,1.1.1.2,no,13,Behind the other routers so no one sees it
C.EXAMPLE.COM,1.1.1.3,no,12.1
d.example.com,1.1.1.4,yes,14
c.example.com,1.1.1.5,no,12,Case a bit loose
e.example.com,1.1.1.6,no,12.3
f.example.com,1.1.1.7,No,15,Guarded by sharks with lasers on their heads
我现在有一个程序,可以读取上面的所有数据。在将结果输出到控制台之前,请先将csv文件转换为数组列表,如所包含的输出文本所示。理想情况下,我最终需要能够比较每一行中的每个不同字段,执行计算等。因此,我希望将每一行保存为数组列表中的对象。我试过这样做,但到目前为止没有成功。有没有一种简单的方法来修改我的程序来做到这一点?此外,如果可能的话,我希望不包括标题和注释。这是我到目前为止的代码-
package crunchify;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class CrunchifyCSVtoArrayList {
public static void main(String[] args) {
BufferedReader crunchifyBuffer = null;
try {
String crunchifyLine;
crunchifyBuffer = new BufferedReader(new FileReader("Crunchify-CSV-to-ArrayList.csv"));
while ((crunchifyLine = crunchifyBuffer.readLine()) != null) {
System.out.println("ArrayList data: " + crunchifyCSVtoArrayList(crunchifyLine) + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (crunchifyBuffer != null) crunchifyBuffer.close();
} catch (IOException crunchifyException) {
crunchifyException.printStackTrace();
}
}
}
// Utility which converts CSV to ArrayList using Split Operation
public static ArrayList<String> crunchifyCSVtoArrayList(String crunchifyCSV) {
ArrayList<String> crunchifyResult = new ArrayList<String>();
if (crunchifyCSV != null) {
String[] splitData = crunchifyCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
crunchifyResult.add(splitData[i].trim());
}
}
}
return crunchifyResult;
}
}
电流输出:
ArrayList数据:[主机名、IP地址、补丁?、操作系统版本、备注]
ArrayList数据:[A.example.COM,1.1.1,NO,11,故障风扇]
ArrayList数据:[b.example.com,1.1.1.2,no,13,在其他路由器后面,所以没有人看到它]
ArrayList数据:[C.EXAMPLE.COM,1.1.1.3,no,12.1]
ArrayList数据:[d.example.com,1.1.1.4,是的,14]
ArrayList数据:[c.example.com,1.1.1.5,no,12,大小写有点松]
ArrayList数据:[e.example.com,1.1.1.6,no,12.3]
ArrayList数据:[f.example.com,1.1.1.7,No,12.2]
ArrayList数据:[g.example.com,1.1.1.6,no,15,由头部装有激光的鲨鱼守卫]
为了更详细地说明我最终需要做的事情,需要打印出哪些路由器需要更新,例如,如果任何路由器低于版本12,则打印出那些路由器需要更新
# 1 楼答案
您应该创建一个自定义类来保存数据。此类的对象表示csv文件中的一行