如何规范 Java 中的 EOL 字符?
我有一个 Linux 服务器和许多具有多种操作系统的客户端。服务器从客户端获取输入文件。 Linux 有行结束符 LF,而 Mac 有行结束符 CR,并且 Windows 有行结束符 CR+LF
服务器需要作为行结束符 LF。使用java,我想确保该文件将始终使用linux eol char LF。我怎样才能实现它?
I have a linux server and many clients with many operating systems. The server takes an input file from clients. Linux has end of line char LF, while Mac has end of line char CR, and
Windows has end of line char CR+LF
The server needs as end of line char LF. Using java, I want to ensure that the file will always use the linux eol char LF. How can I achieve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
你能试试这个吗?
Could you try this?
结合两个答案(由 Visage 和 eumiro 提供):
编辑: 阅读评论后。线。
System.getProperty("line.separator")
则没有用。在将文件发送到服务器之前,打开它替换所有 EOL 并回写
请确保使用 DataStreams 来执行此操作,并以二进制形式写入
replaceAll
方法有两个参数,第一个是要替换的字符串,第二个是替换的字符串。但是,第一个被视为正则表达式,因此'\'
会以这种方式解释。所以:Combining the two answers (by Visage & eumiro):
EDIT: After reading the comment. line.
System.getProperty("line.separator")
has no use then.Before sending the file to server, open it replace all the EOLs and writeback
Make sure to use DataStreams to do so, and write in binary
The
replaceAll
method has two arguments, the first one is the string to replace and the second one is the replacement. But, the first one is treated as a regular expression, so,'\'
is interpreted that way. So:这是一个处理 EOL 问题的综合帮助程序类。它部分基于 tyjen 发布的解决方案。
Here is a comprehensive helper class to deal with EOL issues. It it partially based on the solution posted by tyjen.
必须为最近的项目执行此操作。下面的方法会将给定文件中的行结尾标准化为运行 JVM 的操作系统指定的行结尾。因此,如果您的 JVM 在 Linux 上运行,这会将所有行结尾标准化为 LF (\n)。
由于使用缓冲流,也适用于非常大的文件。
Had to do this for a recent project. The method below will normalize the line endings in the given file to the line ending specified by the OS the JVM is running on. So if you JVM is running on Linux, this will normalize all line endings to LF (\n).
Also works on very large files due to the use of buffered streams.
使用
这将为您提供(本地)EOL 字符。然后,您可以使用对 incomi 文件的分析来确定它的“风味”并进行相应的转换。
或者,让您的客户标准化!
Use
That will give you the (local) EOL character(s). You can then use an analysis of the incomifile to determine what 'flavour' it is and convert accordingly.
Alternatively, get your clients to standardise!
对于 HTML:
For HTML:
从 Java 12 开始,您可以使用
它隐式规范 EOF 字符。
或者更明确地说
Since Java 12 you can use
which implicitly normalizes the EOF characters.
Or more explicitly
解决方案更改路径中以递归搜索结尾的文件
solution to change the file ending with recursive search in path
尽管 String.replaceAll() 的编码更简单,但它应该表现得更好,因为它不经过正则表达式基础结构。
Although String.replaceAll() is simpler to code, this should perform better since it doesn't go through the regex infrastructure.