有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析txt文件,该文件使用opencsv阅读器将分隔符作为列值的一部分

我有一个制表符分隔的文本文件,我想用openscsv解析它并上传到数据库。我使用CSVReader()解析文件。问题是,某些列值中有选项卡。例如,一列以一个制表符结尾,然后它有另一个制表符,用于将它与下一列分开

我在解析这个文件时遇到问题。如何避免分隔符作为值的一部分

This是我试图解析的文件。每行有2列,共5行。第一行是标题。但是,当我使用以下代码解析它时,只得到3行:

CSVReader reader = new CSVReader(new FileReader("input.txt"), '\t');
String[] nextLine;
int cnt = 0;
while ((nextLine = reader.readNext()) != null) {
    if (nextLine != null) {
        cnt++;
        System.out.println("Length of row "+cnt+" = "+nextLine.length);
        System.out.println(Arrays.toString(nextLine));
    }
}

*******更新********

执行正常的读取行(如以下)将打印5行:

BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int lines = 0;
while(br.readLine() != null){
    lines++;
}
System.out.println(lines);

共 (1) 个答案

  1. # 1 楼答案

    1. 在数据上加引号-这里是CSVReaderTest中修改的单元测试,它显示引号将起作用:

      @Test
      public void testSkippingLinesWithDifferentEscape() throws IOException
      {
      
          StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE);
          sb.append("Skip this line?t with tab").append("\n");   // should skip this
          sb.append("And this line too").append("\n");   // and this
          sb.append("a\t'b\tb\tb'\t'c'").append("\n");  // single quoted elements
          CSVReader c = new CSVReader(new StringReader(sb.toString()), '\t', '\'', '?', 2);
      
          String[] nextLine = c.readNext();
      
          assertEquals(3, nextLine.length);
      
          assertEquals("a", nextLine[0]);
          assertEquals("b\tb\tb", nextLine[1]);
          assertEquals("c", nextLine[2]);
      }
      

    如果这不起作用,请发布您输入的一些行。txt。当我点击这个链接时,它会把我带到某个试图向我出售dropbox克隆的网站