我有如下所示的 csv 文件
账号、原因
1234567890,添加
2345678901,dfg
我编写了如下代码来打印 csv 文件中的所有数据
public CSV(){
public static void main(String[] args){
CSVReader csvreader = new CSVReader ( new FileReader(file name);
List<String> lines = csvreader.readAll();
for(String[] line:lines){
for(int i=0; i<line.length; i ++){
Sop(line[i]);
}
Sop(“/n”);
}
}
}
我的要求是打印csv文件中第一列的最后6位数字
账号 567890 678901
有人可以帮我吗
你可以这样做:
public static void readDataFromCustomSeparator(String file) {
try {
// Create object of filereader
// class with CSV file as a parameter.
FileReader fileReader = new FileReader(file);
// Create CSVParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(',').build();
// Create CSVReader object with
// parameters fileReader and parser
CSVReader csvReader = new CSVReaderBuilder(fileReader)
.withCSVParser(parser)
.build();
// Read all data at once
List<String[]> allData = csvReader.readAll();
// Process Data
for (String[] row : allData) {
// Ensure that the row has at least one element
if (row.length > 0) {
// Get the first column
String firstColumn = row[0];
// Get the last six digits of the first column
String lastSixDigits = firstColumn.length() >= 6
? firstColumn.substring(firstColumn.length() - 6)
: firstColumn;
// Print or use the last six digits
System.out.println(lastSixDigits);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
此代码片段使用 OpenCSV 库从 CSV 文件读取数据,重点关注自定义分隔符并仅处理第一列。下面提供的代码片段已根据 https://www.geeksforgeeks.org/reading-csv-file-java-using-opencsv/ 上提供的指南进行了修改。更多示例和解释请参考原版指南。