System.lineSeparator() 的等价物只包括回车符吗?

huangapple go评论66阅读模式
英文:

Is there an equivalent of System.lineSeparator​() for just the carriage return?

问题

在Windows上输出\r并在Unix上不输出任何内容的标准库方法是否可用?(即相当于System.lineSeparator(),但完全不输出换行字符)

  • 我有一些单元测试,用于检查输出到日志记录器的行是否与预期值匹配(通过存根进行测试)。

  • 当在Windows上运行时,这些测试失败,因为字符串包含回车符,即在Unix上输出Foo::Bar,在Windows上输出Foo\r::Bar。这是我第一次看到\r单独生成的情况。

这显然可以自己实现,但希望代码对未来的开发人员来说尽可能明显,因此希望避免不必要的重新实现。不寻找第三方库来执行此操作,只是想知道是否有标准的Java库覆盖了这一需求。

英文:

Is there a standard library method available that will output \r where needed on Windows and nothing for Unix? (i.e. equivalent to System.lineSeparator() except without outputting the newline character at all)

  • I have some unit tests that are checking that lines output to a
    logger are matching the expected values (tested via a stub).

  • These are failing when ran on Windows, as the strings contained a
    carriage return — i.e. it will output Foo::Bar on Unix or
    Foo\r::Bar on Windows. This is the first time that I've seen a \r
    getting generated on its own.

This is obviously easy to roll my own, but want the code to be as obvious as possible for future developers so looking to avoid reimplementing if not needed. Not looking for 3rd party libraries that do this, just if it is something covered by the Standard Java libs.

答案1

得分: 4

如果在Windows上测试失败,这意味着你的代码假定行分隔符是\n。听起来在你的代码中的某个地方(无论是在应用程序代码还是测试代码中),你有类似以下的内容:

String removeLineBreaks(String str) {
    return str.replace("\n", "");
}

显然,这是一个错误:在Windows上,它会保留回车符。

你应该尝试找到有问题的平台相关代码。例如,上面的代码应该更改为:

String removeLineBreaks(String str) {
    // "\\R" 适用于Java 8+,在旧版本中使用 "\\r?\\n"。感谢Joop的建议!
    return str.replaceAll("\\R", "");
}
英文:

If the tests are failing on windows, it means that you have code that assumes the line separator is \n. It sounds like somewhere in your code (either in application code or in test code) you have something like:

String removeLineBreaks(String str) {
    return str.replace("\n", "");
}

and this is obviously a bug: on Windows, it will leave the carriage return untouched.

You should try to find the buggy platform dependent code. For example, the above should be changed to:

String removeLineBreaks(String str) {
    // "\\R" works in Java 8+, use "\r?\n" in older versions. Thank you Joop for this!
    return str.replaceAll("\\R", "");
}

答案2

得分: 3

这将移除最后的换行符(在Windows和Linux上都需要),仅在Windows的情况下保留回车符\r

英文:

Well you could use:

System.lineSeparator().replaceAll("\n$", "")

This would remove the final newline (required on both Windows and Linux), leaving behind the carriage return \r in the case of Windows only.

huangapple
  • 本文由 发表于 2020年8月3日 20:53:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63229826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定