How can I normalize the EOL character in Java?

后端 未结 8 950
醉话见心
醉话见心 2020-12-29 03:13

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 cha

8条回答
  •  悲&欢浪女
    2020-12-29 03:26

    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

    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
    //..
    

    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
    

提交回复
热议问题