Java.csv打印报表问题



当前正在处理一个项目,该项目导入.csv文件(21行20列(,将其捕获到数组中,然后打印电子表格中的特定单元格。。。当前遇到一个问题,导致输出为20行1列,为"null"。除了输出中的第二行似乎是文件中的最后一行第二列单元格。Null是怎么回事,为什么它要提取最后一行数据?谢谢各位的意见。

public class cvsPull {
public String[][] myArray;
String csvFile = "Crime.csv";
public Class csvPull() {

myArray = new String[20][20];

try {
s = new Scanner (new BufferedReader(new FileReader(csvFile)));
while (s.hasNext()) {
int theRow = 1;
int theCol = 0;
InputLine = s.nextLine();
String[] InArray = InputLine.split(",");
for (String InArray1 : InArray) {
myArray[theRow][theCol] = InArray1;
theCol++;
if (theCol==20) {
theCol=0;
theRow++;
}
// System.out.println(myArray[theRow][theCol]);
}
} 
for (String[] theString : myArray) {
System.out.println(theString[1]);
}
} catch (IOException ioe) {
System.out.println("incorrect file name" + ioe.getMessage());
}
}

在每个循环开始时将行计数器重置为1:

while (s.hasNext()) {
int theRow = 1;
int theCol = 0;

这意味着文件的每一行都被写入内存中的同一位置。此外,行的第一个索引是0,与列不同,因此您最初需要将其设置为0:

int theRow = 0;
while (s.hasNext()) {
int theCol = 0;

我建议使用lib读取CSV文件:https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/

import com.opencsv.CSVReader;
import java.io.FileReader;
import java.io.IOException;
public class CSVReaderExample {
public static void main(String[] args) {
String csvFile = "/Users/mkyong/csv/country3.csv";
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(csvFile));
String[] line;
while ((line = reader.readNext()) != null) {
System.out.println("Country [id= " + line[0] + ", code= " + line[1] + " , name=" + line[2] + "]");
}
} catch (IOException e) {
e.printStackTrace();
}

}
}

最新更新