Here is a code for writing a text file from console but i have problem regarding its portability.

import java.io.*;
class KtoD {
public static void main(String args[])
throws IOException {
String str;
FileWriter fw;
BufferedReader br =
new BufferedReader(
new InputStreamReader(System.in));

try {
fw = new FileWriter("test.txt");
}
catch(IOException exc) {
System.out.println("Cannot open file.");
return ;
}
System.out.println("Enter text ('stop' to quit).");
do {
System.out.print(": ");
str = br.readLine();
if(str.compareTo("stop") == 0) break;
str = str + "\r\n"; // <-----------------------------add newline
fw.write(str);
} while(str.compareTo("stop") != 0);
fw.close();
}
}

In above code line no.23 where i have used "\r\n" is only applicable for Windows next line delimiter but if i want to make it universal what should i apply ie for Linux and Mac as well.
I have learned to use "\n" on Linux and "\r" on Mac but its dirty and fast rule as it requires changing the source code each time while switching the systems.

Edited 6 Years Ago by linkingeek: n/a

And, by the way, line separator in mac OS X is \n, not \r. It's like any unix. Not that you should be hardcoding it, mind you, you should use the system properties, that's why they're there. But it's worth knowing that, since there aren't a whole lot of pre-OSX macs running around these days as far as I can see.

Help me using

public static String newline = System.getProperty("line.separator");

in above code (program is just to write txt file)

Edited 6 Years Ago by linkingeek: n/a

Append "newline" anywhere you want to have a line break in your file.

String brokenString = "some text" + newline + "some other text";

will print as

some text
some other text


Okay?

This article has been dead for over six months. Start a new discussion instead.