Reputation: 7709
i have a software that creates a file which i send to a bank software that reads the file.
But this software is rejecting my file because it says my file does not have CRLF
as line separator.
Until now, the file was only created on windows machines, and for line separator i use always "\r\n"
.
I searched about it and found out that if i do it on windows, it generates in a different way than generating on linux or mac.
But how can i always generate CRLF
independent of platform?
UPDATE 1
This is the method i use to create the file, i replace all \r\n for \n and then \n to \r\n, just to ensure that when whoever calls this method passing only \n as line separator, the file will be generated correctly with \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);
}
}
Upvotes: 1
Views: 1214
Reputation: 533530
The \r\n
always prints two characters CR and LF on all platforms. From http://docs.oracle.com/javase/tutorial/java/data/characters.html
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
You can test this yourself 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 a Ubuntu machine prints
0x0d
0x0a
Upvotes: 2