1 回答
TA貢獻1815條經(jīng)驗 獲得超10個贊
最簡單的方法是使用掃描儀并讀取第一行。
通過使用split()with,作為分隔符,您可以獲得一個數(shù)組,它的長度就是您想要的。
public static int getFileColumnsNumber(String filename) {
File file = new File(filename);
Scanner scanner;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
}
int number = 0;
if (scanner.hasNextLine()) {
number = scanner.nextLine().split(",").length;
}
scanner.close();
return number;
}
public static void main(String[] args) {
String filename = "test.txt";
System.out.println(getFileColumnsNumber(filename));
}
添加回答
舉報
