读取文件时,我可以使用EOF或EOL以外的其他稀释剂

时间:2012-03-14 10:27:34

标签: java

我想解析一个文件并使用2'新行' (\ n)作为稀释而不是EOL并将其添加到字符串对象中。

这是算法 -

1. While end of file is not reached
2. Read a file until you hit 2 \n's or eof is reached
  put that contents as a string to a List object. 
3. go to 1.

2 个答案:

答案 0 :(得分:1)

您可以使用Scanner.useDelimiter()方法。

public Scanner useDelimiter(String pattern)
  

将此扫描仪的分隔模式设置为由其构造的模式   指定的字符串。

According to JLS新行

  

LineTerminator:

the ASCII LF character, also known as "newline"

the ASCII CR character, also known as "return"

the ASCII CR character followed by the ASCII LF character

答案 1 :(得分:1)

您可以使用任何所需的分隔符。如果你use Scanner you can set the delimiter

注意:新行通常为(\r\n|\r|\n),以支持新行的三种变体。

在您的情况下,最简单的解决方案可能是

String[] paragraphs = FileUtils.readFileAsString(filename)
                               .split("(\r\n|\r|\n){2}");