【问题标题】:How to read lines from a file that has commas and semi colons in Java如何从Java中包含逗号和分号的文件中读取行
【发布时间】:2014-03-18 04:33:52
【问题描述】:

我知道我可以使用文件阅读器类。但是在阅读一行中的单独文本部分时,我对实现感到困惑。

文件中的每一行都有名称(名字和姓氏由空格分隔),但使用逗号分隔 UKNOWN 的全名集。然后使用分号分隔行内的部分。下一部分由街道名称组成(每个街道名称也由逗号分隔)。

我要做的是将全名读入字符串的ArrayList,当到达分号时,街道名称应插入单独的字符串ArrayList。

如果我能得到一个关于如何继续实施的简短示例,我可以自己完成整个事情。

注意:它必须从文本文件中读取。每行将是全名和街道名称的单独测试用例。

编辑:

以下是输入示例: 詹姆斯·库珀,约翰·埃文斯,亚伯·林肯;杰克逊街,没办法,阿斯彭路

输出: 名称的数组列表包含 = James Cooper、John Evans、Abe Lincoln(每个用逗号分隔)

街道名称的数组列表持有= Jackson st,No way,Aspen Way(每个用逗号分隔)

【问题讨论】:

  • 我认为样本输入和预期输出会比“文本结构”的口头描述更受关注
  • 如果您懒得发布这些行的实际示例,我们也不会费心尝试解释您想要的内容。
  • 我刚刚进行了编辑。为迟到表示歉意。

标签: java text-parsing


【解决方案1】:

最简单的做法可能是将整行读入String,然后多次使用Stringsplit()

String line; // Put the line in here however you're reading from the file.
String[] sections = line.split(";");
// Assuming you know there are always two sections, names and addresses:
String[] names = sections[0].split(",");
String[] addresses = sections[1].split(",");

// Convert arrays into ArrayLists if you actually need to
List<String> namesList = new ArrayList<>( Arrays.asList( names ) );
List<String> addressList = new ArrayList<>( Arrays.asList( addresses ) );

【讨论】:

    【解决方案2】:

    Scanner 类足以满足所有这些要求。您必须适当地使用方法useDelimiter(),具体取决于您要使用的分隔符(即分隔字符/字符串)。

    【讨论】:

      【解决方案3】:

      如果您不介意引入额外的依赖项,请查看 OpenCSV (http://opencsv.sourceforge.net/)。

      这是一个非常基本的示例,它读取一行(称为“nextLine”),然后将每个元素添加到 dataArray 中。当它调用 reader.readNext() 时,这将变为一个新行。如果您确定只有两行数据,您可以替换“while”语句并首先对名称数组进行硬编码,然后调用 readNext(),然后调用街道名称数组。

          //Create the ArrayList to hold data
          ArrayList<String> dataArray =  new ArrayList<String>(); 
      
          //openCSV reader to parse the CSV file
          CSVReader reader = new CSVReader(new FileReader(f));
      
          //nextLine array contains a an entire row of data,
          //Each element represents a cell in the spreadsheet.
          String[] nextLine;
      
          //Iterate though the CSV while there are more lines to read
          while((nextLine = reader.readNext()) != null)
          {
                          //Iterate through the elements on this line
              for(String s : nextLine)
              {
                  dataArray.add(s);
              }
          }
      

      来源:http://opencsv.sourceforge.net/#how-to-read

      -卡兹

      【讨论】:

      • 现在我看到了您的输入数据,我认为这不起作用,但真实性解决方案看起来不错。
      猜你喜欢
      • 2023-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      相关资源
      最近更新 更多