【问题标题】:Deciding newline character at runtime [duplicate]在运行时确定换行符[重复]
【发布时间】:2013-07-22 16:57:43
【问题描述】:

我正在读取一个文件,其中一个段落由换行符分隔。

Line 1
Line 2
Line 3

Line 4
Line 5
Line 6

在这里,我阅读了第 1、2、3 行,然后是第 4、5、6 行。

while (there are still more paragraphs) {
  String paragraph = new Scanner(new File("testdata.txt")).useDelimiter("\n\n").next();
}

分隔符“\n\n”用于识别段落而不是行。现在,分隔符在少数系统中可以变为“\r\n\r\n”,在其他少数系统中可以变为“\n\n”。有没有办法在运行时识别并使用它?我正在寻找类似的东西:

String delimiter = getNewLineCharYourself();
String paragraph = new Scanner(new File("testdata.txt")).useDelimiter(delimiter).next();

【问题讨论】:

  • 检测操作系统并在适当的时候使用\r\n(AFAIK 仅 Windows 使用)或\n
  • @m0skit0 不要重新发明轮子。检查下面的答案。
  • @LuiggiMendoza 谁说他必须自己实现它?这只是一个提示;)

标签: java


【解决方案1】:

你正在寻找

System.getProperty("line.seperator");

【讨论】:

  • System.lineSeparator()反正+1
【解决方案2】:

看看这个:

String newLine = String.format("%n"); 
//       %n becomes newline     ^^

或者:

System.getProperty("line.separator");

或者,在 Java 7 中:

System.lineSeparator();

从这里:How do I get a platform-dependent new line character?

【讨论】:

  • 应该将问题标记为重复而不是重复答案!
  • 你完全正确
【解决方案3】:

您可以直接抓取整个文件,然后拆分数据:

for ( String line : "the entire file".split( System.getProperty("line.separator") )
{
     System.out.println( line );
}

是通用换行符。

另一种方法:

BufferedReader bufferedReader = new BufferedReader( new FileReader( "absolute file path" ) );

String line;

while ( ( line = bufferedReader.readLine() ) != null)
{
     System.out.println( line );
}

【讨论】:

    【解决方案4】:

    jlordo 怎么说。或者使用BufferedReader

    File file = new File("myFile.txt");
    if (file.exists() && file.canRead()) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = null;
            while ((line = br.readLine())!= null) {
                if (!line.trim().isEmpty()) {
                    // TODO something with your line
                }
            }
        } 
        catch (Throwable t) {
            // TODO handle this
            t.printStackTrace();
        }
        finally {
            // attempting to close
            if (br != null) {
                try {
                    br.close();
                }
                catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }
    }
    

    【讨论】:

    • 为什么不使用try with resources 来摆脱finally 中的烂摊子?
    • @jlordo 因为我使用 Java 6 :D
    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 2018-11-29
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2014-06-25
    相关资源
    最近更新 更多