2 回答

TA貢獻1934條經驗 獲得超2個贊
如果您的 CSV 文件始終包含指示表列名稱的標題行,那么只需捕獲該行并將其拆分,以便將這些列名稱放入字符串數組(或集合,或其他)中。該數組的長度決定了每個記錄數據行預期可用的數據量。一旦你有了列名,事情就變得相對容易了。
如何獲取 CSV 文件路徑及其格式類型顯然取決于您,但以下是如何執行手頭任務的一般概念:
public static void readCsvToConsole(String csvFilePath, String csvDelimiter) {
String line; // To hold each valid data line.
String[] columnNames = new String[0]; // To hold Header names.
int dataLineCount = 0; // Count the file lines.
StringBuilder sb = new StringBuilder(); // Used to build the output String.
String ls = System.lineSeparator(); // Use System Line Seperator for output.
// 'Try With Resources' to auto-close the reader
try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
while ((line = br.readLine()) != null) {
// Skip Blank Lines (if any).
if (line.trim().equals("")) {
continue;
}
dataLineCount++;
// Deal with the Header Line. Line 1 in most CSV files is the Header Line.
if (dataLineCount == 1) {
/* The Regular Expression used in the String#split()
method handles any delimiter/spacing situation.*/
columnNames = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
continue; // Don't process this line anymore. Continue loop.
}
// Split the file data line into its respective columnar slot.
String[] lineParts = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
/* Iterate through the Column Names and buld a String
using the column names and its' respective data along
with a line break after each Column/Data line. */
for (int i = 0; i < columnNames.length; i++) {
sb.append(columnNames[i]).append(": ").append(lineParts[i]).append(ls);
}
// Display the data record in Console.
System.out.println(sb.toString());
/* Clear the StringBuilder object to prepare for
a new string creation. */
sb.delete(0, sb.capacity());
}
}
// Trap these Exceptions
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
使用這種方法,您可以擁有 1 到數千個列,這并不重要(并不是說您在任何給定記錄中都會有數千個數據列,但是嘿....您永遠不知道...哈哈)。并使用此方法:
// Read CSV To Console Window.
readCsvToConsole("test.csv", ",");

TA貢獻1719條經驗 獲得超6個贊
如果始終有 3 個屬性,我將讀取 csv 的第一行并在具有三個字段的對象中設置值:attribute1、attribute2 和 attribute3。我將創建另一個類來保存三個值并讀取之后的所有行,每次創建一個新實例并在數組列表中讀取它們。要打印,我只需每次將屬性類中的值與每組值一起打印即可。
添加回答
舉報