【问题标题】:How to handle a new line when reading a file using Java使用Java读取文件时如何处理新行
【发布时间】:2015-07-16 12:59:47
【问题描述】:

我正在尝试读取一个巨大的文件,其中 新行 由no space、comma、new line character 或任何内容表示。

示例: line1element1、line1element2、line1element3、line2element1、line2element2 等..

该文件是csv,我正在阅读它,如下所示:

public static void main(String[] args) throws Exception {
    ArrayList<String> list = new ArrayList<>();
    String element;
    String filename = "E:\\csv.csv";
    Scanner scanner = new Scanner(new File(filename));
    scanner.useDelimiter(",");

    for (int i = 0; i < 50; i++) {
        element = scanner.next();
        list.add(element);

    }
    System.out.print(list);
}

这会导致问题,因为一行中的 element50 与 element51 组合在一起,尽管它应该是一个新行。

【问题讨论】:

    标签: java arrays csv


    【解决方案1】:

    为此使用BufferedReader:

    String filename = "E:\\csv.csv";
    BufferedReader fileReader = null;
    
    //Delimiter used in CSV file
    final String DELIMITER = ",";
    
    String line = "";
    //Create the file reader
    fileReader = new BufferedReader(new FileReader(filename ));
    
    //Read the file line by line
    while ((line = fileReader.readLine()) != null)
    {
        //Get all tokens available in line
        String[] tokens = line.split(DELIMITER);
        for(String token : tokens)
        {
            //Print all tokens
            System.out.println(token);
        }
    }
    

    【讨论】:

    • 我不需要捕获吗?
    • 此外,这会将数据输出为仅 1 个大列,而不是识别多行。
    • 这是一个可怕的解决方案,CSV 解析有很多错综复杂的地方。对于初学者,如果任何值带有换行符,readLine 将不起作用。 String.split 将错误地处理包含逗号字符的引用值。为此,请使用 CSV 解析器,而不是自己创建。
    • 忘了说:这也非常慢。尝试在一个大文件上运行这段代码,然后自己看看。
    【解决方案2】:

    使用 BufferedReader,而不是 Scanner

    File f= ...;
    BufferedReader br = new BufferedReader(new FileReader(f));
    String line;
    while ((line = br.nextLine()) != null) {
      String[] columns = line.split(",");
    }
    

    【讨论】:

      【解决方案3】:

      为什么不使用来自 Apache Commons 的 CSVParser 或 OpenCSV?

      这里的例子:

      如果您坚持手动执行此操作,请使用其他 cmets 提到的 BufferedReader。

      【讨论】:

        【解决方案4】:

        根据您的描述,您的文件似乎没有每列的标题。使用 uniVocity-parsers 为您执行此操作 - 它比 Commons CSV 和 OpenCSV 快 3 倍,并且包含许多功能。

        // you have many configuration options here - check the tutorial. By default values are trimmed and blank lines skipped.
        CsvParserSettings settings = new CsvParserSettings();
        
        CsvParser parser = new CsvParser(settings);
        
        List<String[]> allRows = parser.parseAll(new FileReader(new File("/path/to/your/file.csv")));
        

        披露:我是这个库的作者。它是开源免费的(Apache V2.0 许可)。

        【讨论】:

          猜你喜欢
          • 2017-03-24
          • 1970-01-01
          • 2015-12-21
          • 2018-04-25
          • 1970-01-01
          • 2022-01-21
          • 2018-05-18
          • 2017-12-11
          • 2018-08-03
          相关资源
          最近更新 更多