【问题标题】:How do I read a CSV File with JAVA如何使用 JAVA 读取 CSV 文件
【发布时间】:2019-10-07 15:05:48
【问题描述】:

我有一个问题,但我还没有找到任何解决方案。以下问题:我必须读取一个看起来像这样的 CSV 文件:

First Name,Second Name,Age,

Lucas,Miller,17,

Bob,Jefferson,55,

Andrew,Washington,31,

作业是用 JAVA 读取这个 CSV 文件并显示如下:

First Name: Lucas

Second Name: Miller

Age: 17

属性名称并不总是相同,因此也可能是:

Street,Number,Postal Code,ID,

Schoolstreet,93,20000,364236492,

("," 必须替换为 ";")

此外,文件地址并不总是相同的。 我已经有了视图等。我只需要模型。

感谢您的帮助。 :))

我已经在 Controller 中有一个 FileChooser 类,它返回一个 URI。

【问题讨论】:

    标签: java file csv


    【解决方案1】:

    如果您的 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", ",");
    

    【讨论】:

      【解决方案2】:

      这是我最近为面试编写的一些代码,可能会有所帮助:https://github.com/KemarCodes/ms3_csv/blob/master/src/main/java/CSVProcess.java

      如果您总是有 3 个属性,我会读取 csv 的第一行并在具有三个字段的对象中设置值:attribute1、attribute2 和 attribute3。我将创建另一个类来保存三个值并读取之后的所有行,每次创建一个新实例并在数组列表中读取它们。要打印,我只需每次将属性类中的值与每组值一起打印。

      【讨论】:

      • 感谢您的回答,但不幸的是,属性可能不止三个...
      • 代码大概可以概括。每列具有相同的名称,因此 col1 是 X col2 isY 等。您可以在逗号上的每一行 String.spilt,将每个值存储为 PairsList,您应该以 List&lt;List&lt;Pair&gt;&gt; 结尾,其中每个List&lt;Pair&gt; 可以映射到一个对象。要打印出来,请确保对象具有toString。使用一对可能有点矫枉过正,但它也可能使生活更易于管理
      猜你喜欢
      • 2022-11-12
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多