如何规范Java中的EOL字符? [英] How can I normalize the EOL character in Java?

查看:164
本文介绍了如何规范Java中的EOL字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Linux服务器和许多拥有许多操作系统的客户端。服务器从客户端获取输入文件。 Linux有行终结char LF,而Mac有行尾char CR,而
Windows有行尾char CR + 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

服务器需要as行尾char LF。使用java,我想确保该文件将始终使用linux eol char 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?

推荐答案

结合两个答案(Visage& eumiro):

Combining the two answers (by Visage & eumiro):

编辑: 阅读评论后。线。
System.getProperty(line.separator)然后没有用。

在将文件发送到服务器之前,打开它替换所有EOL和回写

确保使用DataStreams这样做,并用二进制写入

String fileString;
//..
//read from the file
//..
//for windows
fileString = fileString.replaceAll("\\r\\n", "\n");
fileString = fileString.replaceAll("\\r", "\n");
//..
//write to file in binary mode.. something like:
DataOutputStream os = new DataOutputStream(new FileOutputStream("fname.txt"));
os.write(fileString.getBytes());
//..
//send file
//..

replaceAll 方法有两个参数,第一个是要替换的字符串,第二个是替换字符串。但是,第一个被视为正则表达式,因此,'\'被解释为这种方式。所以:

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:

"\\r\\n" is converted to "\r\n" by Regex
"\r\n" is converted to CR+LF by Java

这篇关于如何规范Java中的EOL字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆