^

PrintStream Class

The printstream class inherits class FilterOutputStream and implements Appendable and Closeable interfaces. PrintStream class adds the functionality to other output streams that have the ability to print various data values conveniently,unlike other output streams, a PrintStream class never throws an IOException, insteats it sets an internal flag that can be tested via checkError() method and the data is flushed automatically. In Other words, the flush() method is automatically invoked after a byte array is written. The PrintSream class enables you to write formatted data to underlying OutputStream. For Example, with PrintStream,int,long and other primitive data types are formatted as text rather than bytes.
The Out object (System.out), which we use to print data on output screen represents an instance of PrintStream class.

Constructors

  1. PrintStream (File fileObject) throws FileNotFoundException
  2. PrintStream (OutputStream object) throws FileNotFoundException
  3. PrintStream (String filename) throws FileNotFoundException
The above constructors create PrintStream class object by creating a connection to the underlying output stream. The OutputStream can be specified by a File object, OutputStream object or by its name (String). Constructors
  1. PrintStream (File fileObject) throws FileNotFoundException.
  2. PrintStream (OutputStream object) throws FileNotFoundException.
  3. PrintStream (String filename) throws FileNotFoundException.
The above constructors create PrintStream class object by creating a connection to the underlying output stream. The OutputStream can be specified by a File object, OutputStream object or by its name (String).
Methods
Some commonly used methods are listed below:
Methods Description
void close() This method closes the stream.
void flush() It flushes the stream.
void print(boolean b) Prints a boolean value.
void print(char ch) Prints a character value.
void print(char[] ary) Prints an array of character value.
void print(double d) Prints a double-precision floating-point number.
void print(float f) Prints a floating point number.
void print(int i) Prints an integer value.
void print(long l) Prints a long integer.
Void print(object obj) This method calls toString() method of object passed as parameter.
void print(String str) Prints a string.
PrintStream printf(String format, Object... args) It is a conversion method to write a formatted string to the output stream using the specified formatted string and arguments
void println() Terminates the current line by writing the line separator string.
void println(boolean b) Prints a boolean and then terminates the line.
void println(char ch) Prints a character and then terminates the line.
void println(char[] ary) Prints an array of characters and then terminates the line.
void println(doubled d) Prints a double-precision floating point and then terminates the line.
void println(float f) Prints a floating-point number and then terminates the line.
void println(Object obj) Prints the string returned by toString() method of object passed as parameter and then terminates the line.
void println(String str) Prints a string and then terminates the line.
void write(byte[] buf, int off, int count) Writes count bytes from the specified byte array(buf) starting from offset off.
void write(int b) Writes the specified byte to the stream.
Implementation
The following program uses various methods of PrintStream class to write data to text file and read the same , line by line using BufferedReader class
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;

class Address
{
	int houseNo;
	int stno;
	String area;

	Address(int h,int s,String ar)
	{
		houseNo=h; stno=s; area=ar;
	}
public String toString()
	{
		return "House no="+houseNo+" Street no.="+stno+" Area="+area;

	}
}
public class PrintStreamClass 
 {
	public static void main(String[] args) throws FileNotFoundException,IOException 
	{
					//Writing In File
	FileOutputStream fos=new FileOutputStream("EmpData.txt");
	PrintStream ps=new PrintStream(fos);
	
	String EmpName="Sandeep Kumar";
	float salary=5000000;//
	
	System.out.println("Writing Employee Name...");
	ps.println("Employee Name:"+EmpName);//writing string
	System.out.println("Writing Employee Salary...");
	ps.println("Salary:"+salary);//writing float
	
	Address adr=new Address(20877, 18, "Ajit Road");
	System.out.println("Writing Employee Address...");
	ps.println("Employee Address:"+adr);// writing object

	fos.close();
	ps.close();
	System.out.println("Writing Process Completed....");
				// Reading from file (line by line)
	BufferedReader rdr=new BufferedReader(new FileReader("EmpData.txt"));
	String line;
	System.out.println("Reading Started...");
	while((line=rdr.readLine())!=null)
	{
		System.out.println(line);
	}
	rdr.close();
	System.out.println("Reading Finished....");
	}
}
            
   OUTPUT
      Writing Employee Name...
      Writing Employee Salary...
      Writing Employee Address...
      Writing Process Completed....
      Reading Started...
      Employee Name:Sandeep Kumar
      Salary:5000000.0
      Employee Address:House no=20877 Street no.=18 Area=Ajit Road
      Reading Finished....
            

Buffered Writer Class

Java.io.BufferedWriter class inherits Writer class directly . This class writes text to character output stream. Instead of writing each character directly in the file it buffers the characters so as to provide for efficient writing of single character , array and string. The buffer size may be specified or the default size (8192 chars) he accepted. The default buffer size is large enough for most purposes. Not all platforms use the newline character (\n) to terminate lines. So a newLine() method is provided, which uses platform's own line seperator as defined by the System property.
It is advisable to wrap a Buffered Writer around any Writer object whose write() operations may be costly, such as FileWriter and OutputStream Writer.

Constructors

  1. Buffered Writer (Writer object)
  2. Buffered Writer (Writer object, int bufferSize)
The above constructors create buffered character-output stream. The first constructor uses default size (8192 chars) for output buffer (an array of char type).
Wheres in second constructor, the size of output buffer is specified by the user.

Buffered Reader Class

java.io.Buffered Reader class inherits Reader class directly. BufferedReader buffer the characters to read characters, arrays and lines. The buffer size may be specified or the default size may be accepted. Its default size is (8192 chars), which is large enough for most purposes.
In general, each request made of a reader cause a corresponding read request to be made of the underlying character or byte stream. Thus, it is advisable to wrap Bufferedreader around any Reader object, whose read() operation may be costly, such as FileReaders and InputStreamReaders.
programs that use DataInputStream for textual input can be replaced with Buffered Reader
Constructors
  • BufferedReader (Reader Object)
  • BufferedReader(Reader object, int bufferSize)
The above construction create buffered Character-Input-Stream. The first constructors uses default size(8192 chars) for input buffer (an array of char type). Whereas, in second constructor, the size of Inputbuffer is specified. In addition to the methods of Reader class (Base Class). The BufferedReader class provides the method nextLine() to read a line of text from underlying reader.
  • String readLine() throws IOException.
It returns null value when end of the stream is reached. Implementation
The Following program uses BufferedReader and BufferedWriter classes . It consist 2 methods i.e writeToFile() & readFromFile().writeToFile() method inputs name,address and college/company from user and writes in the specified file. Whereas, readLine() method reads text line by line and shown it on the output Screen
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderWriter 
{
static void writeToFile()
	{
		try
		{
			//Input Data from User
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("Enter Your Name:");
			String s = br.readLine();
			System.out.print("Enter Your Address:");
			String a = br.readLine();
			System.out.print("Enter Your College/Company Name:");
			String cc = br.readLine();
			// Write the above in file
			BufferedWriter bufw=new BufferedWriter(new FileWriter("urdata.txt",true));
			bufw.write("Name:"+s);
			bufw.newLine();
			bufw.write("Address:"+a);
			bufw.newLine();
			bufw.write("College/Company:"+cc);
			bufw.newLine();
			bufw.flush();//clear the buffer
			bufw.close();//must be closed
			System.out.println("Writing Process Completed.......");
		
		}
		catch(Exception ex){ex.printStackTrace();}
		
	}
static void readFromFile()
	{
	try{
			BufferedReader rdr=new BufferedReader(new FileReader("urData.txt"));
			String line;
			System.out.println("\nReading Data From File...");
			while((line=rdr.readLine())!=null)
			{
				System.out.println(line);
			}
			rdr.close();
			System.out.println("Reading Finished....");
		}
	catch(IOException ex){ ex.printStackTrace();}
	
	}
	public static void main(String[] args)
	{
	writeToFile();
	readFromFile();

	}

}
                
    OUTPUT
     Enter Your Name:Rajesh Bansal
     Enter Your Address:Ajit Road
     Enter Your College/Company Name:BCE & SST
     Writing Process Completed.......
     Reading Data From File...
     Reading Started...
     Employee Name:Sandeep Kumar
     Salary:5000000.0
     Employee Address:House no=20877 Street no.=18 Area=Ajit Road
     Reading Finished....
                

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap