所以我这里有这个方法应该返回csv文件中的行数。很简单吧?事情是,而不是返回csv文件中的行数(在这种情况下为15)它返回66.老实说,我知道为什么会发生这种情况。我检查了csv文件,并确认它确实是15行,没有空行。也有人知道为什么我的Jpanes不显示没有这三行注释行,我的ide说变量没有在任何地方使用。
public static int getLineCount(){
int line=0;
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data =inputStream.next();//this line is useless but the program doesn't display with out it
String[] values = data.split(",");//this line is useless but the program doesn't display with out it
i++;//this line is useless but the program doesn't display with out it
line++;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
return line;
}
答案 0 :(得分:0)
使用BufferedReader而不是Scanner:
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
while(reader.readLine() != null){
line++;
}
答案 1 :(得分:0)
public static int getLineCount(){
String csvFilePath = "C:\\Users\\uzochi\\desktop\\txt.csv";
String line = "";
int numberOfLines=0;
try {
BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
while (( line = br.readLine()) != null) {
numberOfLines++;
}
}catch(FileNotFoundException e){
//
}catch (IOException ex) {
//
}
return numberOfLines;
}