Streams - Input/output
- Stream is Byte Based, Input stream can be used to read bytes, output stream can be used to write bytes.
- Stream is used to binary input/output. Eg- Java .class file
- Read or write 1 byte (8-bit) at a time
- Streams can be handy for machine-oriented data.
Readers/Writers
- Reader is used to character input/output
- Example -
- FileReader is used for reading text files in platform default encoding.
- Now question comes comes, What is Platform default encoding?
- Platform default encoding means the encoding used by the operating system on which the JVM is running.
- Example - Platform default encoding is user specific setting.
- Windows (in US) - it's often CP1250,
- Windows (in Europe) - it's often CP1252.
- Windows (in China) - it's often Big5.
Buffered - Like BufferedInputStream and BufferedOutputStream | BufferedReader and BufferedWriter
- Buffered is buffered, it's faster and hence improves performance.
- Let’s see how BufferedInputStream works >
- BufferedInputStream reads bytes from another InputStream (Eg - FileInputStream)
- So, BufferedInputStream is wrapper formed on FileInputStream.
FileInputStream fis = new FileInputStream("c:/myFile.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
- A BufferedInputStream enables another input stream to buffer the input and supports the mark and reset methods.
An internal buffer array is created when the BufferedInputStream is created.
As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time.
- BufferedInputStream is much faster as compared to FileInputStream.
when BufferedInputStream.read() is called mostly data is read from the buffer.
When data is not available available in buffer a call is made to read system file and lot of bytes are kept in buffer.
Example -
A BufferedInputStream reads from FileInputStream, will request lot of data from the FileInputStream (128 bytes or so… not exact figure). Thus only 2 calls will be made for reading 256 bytes from file.
|
Another Example - Real world Example - You must have seen youtube videos where video is buffered before you actually start watching it, buffering overall improves your video watching experience.
|
BufferedReader is used to read characters from file and BufferedWriter is used to write characters in file.
RELATED LINKS>
Difference between Stream (FileInputStream) and Reader (FileReader) in java file
Difference between FileInputStream and BufferedInputStream in java file IO
Labels:
Core Java
File IO/File handling