如何从 java 中的 csv 文件中读取一行的特定列
How to read a specific column of a row from a csv file in java
我有以下代码从 csv 文件中读取数据,它遍历行,但我不知道如何遍历特定列(例如该行的前 2 列)为了找到数据。有什么建议吗?
String file = "pathToCsvFile";
BufferedReader reader = null;
String line = "";
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String[] row = line.split(",");
for(String index:row) {
//HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
我知道“,”是您的分隔符,所以关键在算法中:
String file = "pathToCsvFile";
BufferedReader reader = null;
String line = "";
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String[] row = line.split(",");
for(int i = 0; i < row.length; i++) {
//HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
if(i < 2){
System.out.println(i+" -> "+row[i]);
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
我有以下代码从 csv 文件中读取数据,它遍历行,但我不知道如何遍历特定列(例如该行的前 2 列)为了找到数据。有什么建议吗?
String file = "pathToCsvFile";
BufferedReader reader = null;
String line = "";
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String[] row = line.split(",");
for(String index:row) {
//HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
我知道“,”是您的分隔符,所以关键在算法中:
String file = "pathToCsvFile";
BufferedReader reader = null;
String line = "";
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String[] row = line.split(",");
for(int i = 0; i < row.length; i++) {
//HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
if(i < 2){
System.out.println(i+" -> "+row[i]);
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}