Reputation: 115
[SOLVED]
Seems like my application isn't the problem. Reading char by char as suggested doesn't show any CR. The error is probably on the receiver side (independent of my application) which, for whatever reason, adds a 0x0D char. Still this can be a good example of how to put \n only.
[/SOLVED]
I have a strange behavior in my application:
I need to end each line with a LF only which should be "\n" as far as I know. Still I'm getting CRLF for every line (as if I was writing "\r\n").
The application is quite complex so I'm pasting here a sample code
private static final String STR1 = "Str_1";
private static final String STR2 = "Str_2";
private static final char NEW_LINE = (char)0x0A;
//private static final String NEW_LINE = "\n";
public static void main(String[] args) {
//They all return CR+LF instead of LF only.
System.out.println("Str_1\nStr_2");
System.out.print(STR1+NEW_LINE+STR2);
try{
FileOutputStream fos = new FileOutputStream("tests\\newline_test.txt");
fos.write((STR1+NEW_LINE+STR2).getBytes()); //The case I'm mostly interested into
fos.close();
} catch (IOException e){
e.printStackTrace();
}
}
I'm using Eclipse with Java6 (forced) on Windows platform (forced).
Is there any setting that could be messing up with this? Or am I missing something?
Upvotes: 0
Views: 2203
Reputation: 4413
Your program is correct. To test, add this code snippet after the file is created i.e. after fos.close()
FileInputStream fis = new FileInputStream("tests\\newline_test.txt");
int read = -1;
while((read = fis.read())!=-1){
System.out.println(read);
}
fis.close();
The output should be :
Str_1
Str_2
Str_1
Str_283
116
114
95
49
10
83
116
114
95
50
Notice that you get only 10
which is the new line character. If the file had a CR then the output should contain 13
too.
Upvotes: 1
Reputation: 276
Cant believe, that this code results in a file with \r\n!
Check the file with a hex dump tool (e.g. you can use "Tiny Hexer") immediately after creation, before you toched the file with any other tool.
Maybe you have opened the file with an editor after creation and the editor wrote back \r\n?
Upvotes: 1
Reputation:
If you are only going to use Windows, you can use 13 and 10 as line separator.
os.write(10);
os.write(13);
If you must ake care of managing crossplatform line separator, I would use this:
System.getProperty("line.separator")
Or this:
String.format("%n")
Hope it helps
Upvotes: 0