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.

Recommended Answers

All 5 Replies

You can get the value for the system your Java program is running on from the system properties. It is essential to do this with portable programs, and you should always assume your program is portable, eg, that it might run as an applet or using Webstart.

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

http://leepoint.net/notes-java/io/10file/sys-indep-newline.html

Look at line.separator in System Properties.

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)

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.