Tuesday, January 15, 2008

The easiest way to print text

The most of us use System.out.println to print to the screen but maybe a more conveniet way is

PrintStream out = System.out;
out.println("print something");


because if you want to redirect your output to a file, you have simply to change the construction of PrintStream as follows:

File myfile = new File("myfile.txt");
PrintStream out = new PrintStream(myfile);


Remember that, if you're writing a command-line program that can be executed everywhere in the filesystem, to precede your filename with the complete path of the working dir

String workingDir = System.getProperty("user.dir") 
+ System.getProperty("file.separator");
File myfile = new File(workingDir+"myfile.txt");

No comments: