Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: print string using PrintStream Class & without System Class
|
Posted: Nov 27, 2003 3:17 PM
|
|
You create a PrintStream object with a constructor which takes an OutputStream object as its argument:
PrintStream public PrintStream(OutputStream out)Create a new print stream. This stream will not flush automatically.
Parameters: out - The output stream to which values and objects will be printed
OutputStream out = System.out; PrintStream ps = new PrintStream(out);
to make the print stream object print something, you call its print method: print public void print(String s)Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
Parameters: s - The String to be printed
ps.print("abcd");
or the println method:
ps.println("abcd"); Since the print stream will not automatically flush yo must call the print stream's flush method:
ps.flush();
and then close the print stream if you are done with it:
ps.close();
Summary:
OutputStream out = System.out; PrintStream ps = new PrintStream(out); ps.print("abcd"); // or ps.println("abcd"); ps.flush(); ps.close();
If you are not allowed to use the System.out OutputStream, you could could construct another OutputStream, you could create any of the subclasses of OutputStream such as FileOutputStream.
FileOutputStream fos = new FileOutputStream("test.txt"); PrintStream ps = new PrintStream(fos); ps.print("abcd"); // or ps.println("abcd"); ps.flush(); fos.close();
Usually you need to put these lines inside a try catch block to check for IOExceptions
|
|