print( ) and println( ) methods which we use for printing the output are the methods of the PrintStream Class. By default when these methods are used with System.out will print the output in the console. But now lets try to implement PrintStream Class for printing the output into a text file using print and println statements as shown in the below example -
PrintStream ps = new PrintStream(new FileOutputStream("abc.txt"));
ps.println("Hi. How are you?");
ps.print("I am doing good");
Output (printed into 'abc.txt' file) -
Hi. How are you?
I am doing good.
Lets implement this on Eclipse IDE -
1. Launch Eclipse IDE, create a new Java Class 'PrintStreamDemo.java' with main( ) method in the existing Java Project 'Project 51' as shown below -
2. Create a PrintStream Class object statement by specifying the 'abc.txt' as an output file as shown below (Resolve import errors) -
3. Add 'throws IOException' to the method declaration to resolve the error as shown below (Resolve import error) -
4. Use println( ) and print( ) methods with the PrintStream Class object as shown below -
5. Close the PrintStream object as shown below -
6. Save & Run the program and observe that println( ) and print( ) methods printed the specified texts as output into the 'abc.txt' file in our project workspace as shown below -
Hence we can use println( ) and print() methods of PrintStream Class to print the output of a program to a desired destination like files etc. In this post, I have explained to print the output to a file. We can also print the output to the other destinations like console etc.
Please comment below to feedback or ask questions.