java - How to correctly write CRLF for maximum portability? -
i have software creates file send bank software reads file. software rejecting file because says file not have crlf
line separator. until now, file created on windows machines, , line separator use "\r\n"
. searched , found out if on windows, generates in different way generating on linux or mac. how can generate crlf
independent of platform?
update 1
this method use create file, replace \r\n \n , \n \r\n, ensure when whoever calls method passing \n line separator, file generated correctly \r\n:
public static void createfile(string filepath,string content){ try{ file parentfile=new file(filepath).getparentfile(); if(parentfile!=null && !parentfile.exists()){ parentfile.mkdirs(); } bufferedwriter bw=new bufferedwriter(new filewriter(filepath)); bw.write(content.replaceall("\r\n","\n").replaceall("\n","\r\n")); bw.flush(); bw.close(); }catch(exception e){ throw new runtimeexception("error creating file", e); } }
the \r\n
prints 2 characters cr , lf on platforms. http://docs.oracle.com/javase/tutorial/java/data/characters.html
\n insert newline in text @ point.
\r insert carriage return in text @ point.
you can test with
filewriter fw = new filewriter("test"); fw.write("\r\n"); fw.close(); fileinputstream fis = new fileinputstream("test"); for(int ch; (ch = fis.read())!=-1;) { system.out.printf("0x%02x%n", ch); } fis.close();
run on ubuntu machine prints
0x0d 0x0a
Comments
Post a Comment