Java String replace EOL with CRLF
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String input = "demo2s.com\n\n\\r\rdemo2s.com"; System.out.println(convertEOLToCRLF(input)); }//from ww w. j a v a 2 s . c o m /** @deprecated Please inline this method. */ public static String convertEOLToCRLF(String input) { return input.replaceAll("(\r\n|\r|\n)", "\r\n"); } }
Converts any instances of "\r" or "\r\n" style EOL into "\n" (Line Feed).
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String input = "demo2s.com\n\n\\r\rdemo2s.com"; System.out.println(convertEOLToLF(input)); }/*from ww w . j a v a2 s.c om*/ /** * Converts any instances of "\r" or "\r\n" style EOLs into "\n" (Line Feed). */ public static String convertEOLToLF(String input) { StringBuilder res = new StringBuilder(input.length()); char[] s = input.toCharArray(); int from = 0; final int end = s.length; for (int i = 0; i < end; i++) { if (s[i] == '\r') { res.append(s, from, i - from); res.append('\n'); if (i + 1 < end && s[i + 1] == '\n') { i++; } from = i + 1; } } if (from == 0) { // no \r! return input; } res.append(s, from, end - from); return res.toString(); } }