java - 如何在java中使用列名读取csv
问题描述
我尝试使用以下代码读取带有索引的列:
int col1;
String msg = null;
int i = 0;
String[] array = null;
File file = new File(csvFileName);
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
array = line.split(";", -1);
// System.out.println(array[col1]);
if (array[col1].equals("")) {
// System.out.println("Cell is blank");
break;
} else {
// System.out.println(array[col1].toString());
i++;
}
}
if (i < (array[col1].length())) {
msg = "Invalid file";
// System.out.println("Invalid File");
} else {
msg = "Valid file";
// System.out.println("valid File");
}
return msg;
例如。
|HEADER 1| HEADER 2| HEADER 3|
|A|B|C|
|D| |F|
当我在 col1 中传递 col 索引时,我无法将列标题文本存储在变量中以打印哪个列具有空白值。
有什么方法可以读取列以验证空白单元格,然后打印列名,结果显示“此列有空白单元格,因此文件无效”
在上表中,如何使用其名称读取列。假设我通过 HEADER 2 它应该读取所有行数据并且如果它找到空白字段
解决方案
根据您的输入数据示例:
|HEADER 1| HEADER 2| HEADER 3|
|A|B|C|
|D| |F|
所以你有一个由 ha 标题行组成的文件,其中有你的列名和数据。
要读取 colimns 名称,您需要以不同的方式解析第一行:
// field separator
String separator = ";";
//...
int i = 0;
Map<String, int> headers = new HashMap<>();
for (String line : lines) {
if (i == 0) {
String[] headLine = line.split(separator);
for (int j = 0; j < headLine.length; j++) {
headLine.put(headLine[j], j);
}
i++;
continue;
}
}
因此,您将每个列名放在地图中并保存列的索引。
地图的大小也是行 len 以检查您是否阅读了所有预期的字段。
然后你读取数据:
int col1 = 1; // assign a valid column index
int fields = 0;
for (String line : lines) {
if (array[col1].equals("")) {
// System.out.println("Cell is blank");
break;
} else {
// System.out.println(array[col1].toString());
fields++;
}
}
if (fields < headers.size()) {
msg = "Invalid file";
// headers[fields] is the name of the column with the empty cell
}
在您的示例col1
中,索引不是列的名称,但您从未使用值设置它,也许这是问题之一。
推荐阅读
- tensorflow - 神经网络具有与目标数据不同的输出形状
- visual-c++ - Cmake,Ninja,BATS,建立在 windows - Clion 风格
- mysql - 似乎无法弄清楚这个mysql错误。在正文中声明。任何帮助都是极好的
- python - 为什么我执行 PCA 后图像文件的大小会增加?
- javascript - 如何为包含制作不敏感的值类型?
- python - 每次运行程序时都有不同的cloudpickle
- discord - 我有这个代码,但我想制作它,这样它就可以给出机器人加入的服务器上有多少成员,它不会给我一个错误
- lua - 如何修复“ServerScriptService.Earthquake:11:尝试使用 'OnServerEvent' 索引 nil”
- python - 如何检查数组的所有值是否彼此相等?
- r - tableone 包:如何从 svydesign 对象中获取优势比和置信区间?