💻Step 23:I/O package 18th+19th hour+code

Learn with youtube video-

💡Definition-

Input/Output package of Java is set of classes which are used to read and write the data.

Important words –

1- Stream- It’s a mediator which connects our program to input and output device.
It’s a continuous flow of data which travel between source and target.

2- Buffer A buffer is a temporary storage area in a computer’s memory that is used to store data that is being transferred from one place to another.

3- Source/Destination – Location of data

4- Byte – The data in a file is typically organized into a series of bytes.

💡Types of streams-

Here is a table comparing input streams and output streams in Java:

Input StreamOutput Stream
Reads data from an external sourceWrites data to an external destination
Subclasses include BufferedReader, DataInputStream, and InputStreamReaderSubclasses include BufferedWriter, DataOutputStream, and OutputStreamWriter
Uses the read() method to read dataUses the write() method to write data
Examples: reading from a file, reading from a network socket, KeyboardExamples: writing to a file, writing to a network socket, Monitor

💡Stream Classes-

Here is a tabular comparison of Byte Stream classes and Character Stream classes in Java:

Byte Stream ClassesCharacter Stream Classes
PurposeReading and writing raw bytes of dataReading and writing characters (text)
Input/Output Typebyte datacharacters (unicode)
ExamplesFileInputStream, FileOutputStream, ByteArrayInputStream, ByteArrayOutputStreamFileReader, FileWriter, CharArrayReader, CharArrayWriter
ConstructorsAccepts a File or String specifying the file path, or an InputStream or OutputStreamAccepts a File or String specifying the file path, or a Reader or Writer
Working with Primitive Data TypesCan use DataInputStream and DataOutputStream to read and write primitive data typesCan use a combination of BufferedReader and PrintWriter to read and write primitive data types
BufferingCan use BufferedInputStream and BufferedOutputStream to improve performanceCan use BufferedReader and BufferedWriter to improve performance
Unicode SupportDoes not support UnicodeSupports Unicode
Note-

The input streams of byte stream classes are similar to the Reader streams of character stream classes
and the output streams are equivalent to Writer streams of character stream classes.

💡ByteStream classes-

Here is a tabular diagram showing the main classes in the java.io package for reading and writing bytes, along with a brief description of each class and a code snippet demonstrating how to use it:

Class nameDescriptionCode snippet (put in any method)
InputStreamAbstract base class for reading bytes from a stream.
OutputStreamAbstract base class for writing bytes to a stream.
FileInputStreamConcrete subclass of InputStream for reading bytes from a file.FileInputStream in = new FileInputStream(“file.txt”);
int b;
while ((b = in.read()) != -1) { System.out.print((char) b);
}
FileOutputStreamConcrete subclass of OutputStream for writing bytes to a file.FileOutputStream out = new FileOutputStream(“file.txt”); out.write(“Hello, world!”.getBytes());
BufferedInputStreamWrapper class for InputStream that reads bytes from a buffer.BufferedInputStream bis = new BufferedInputStream(new FileInputStream(“file.txt”);
int c;
while ((c = bis.read()) != -1) { System.out.print((char)c);
}
bis.close();
BufferedOutputStreamWrapper class for OutputStream that writes bytes to a buffer.BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(“file.txt”);
String data = “This is some data to write to the file.”;
bos.write(data.getBytes());
bos.flush();
bos.close();
DataInputStreamWrapper class for InputStream that can read primitive data types.FileInputStream fis = new FileInputStream(“data.bin”); DataInputStream dis = new DataInputStream(fis);
int i = dis.readInt();
double d = dis.readDouble();
boolean b = dis.readBoolean();
String s = dis.readUTF();
dis.close();







DataOutputStreamWrapper class for OutputStream that can write primitive data types.FileOutputStream fos = new FileOutputStream(“data.bin”); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(123);
dos.writeDouble(3.14); dos.writeBoolean(true); dos.writeUTF(“Hello World”); dos.close();
ObjectInputStreamWrapper class for InputStream that can read objects from a stream.User user = new User(“Alice”, 25); FileOutputStream fileOut = new FileOutputStream(“user.ser”); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(user); out.close(); fileOut.close();
ObjectOutputStreamWrapper class for OutputStream that can write objects to a stream.FileInputStream fileIn = new FileInputStream(“user.ser”); ObjectInputStream in = new ObjectInputStream(fileIn); User deserializedUser = (User) in.readObject(); in.close(); fileIn.close();
ByteArrayInputStreamConcrete subclass of InputStream for reading from a byte array.byte[] data = {1, 2, 3, 4, 5}; ByteArrayInputStream in = new ByteArrayInputStream(data); int b; while ((b = in.read()) != -1) { System.out.print(b + ” “); }
ByteArrayOutputStreamConcrete subclass of OutputStream for writing to a byte array.ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 1; i <= 5; i++) { out.write(i); } byte[] data = out.toByteArray(); for (int b : data) { System.out.print(b + ” “); }

💡-Character Stream Class-

Detailed hierarchy of CharacterStream class –


    - Reader
        - BufferedReader
        - InputStreamReader
        - FileReader
        - CharArrayReader
        - StringReader
        - PipedReader
        - FilterReader
            - PushbackReader
        - LineNumberReader
    - Writer
        - BufferedWriter
        - OutputStreamWriter
        - FileWriter
        - CharArrayWriter
        - StringWriter
        - PipedWriter
        - FilterWriter
ClassDescriptionExample
ReaderAbstract class for reading character streams.
WriterAbstract class for writing character streams.
FileWriterSubclass of Writer class and it is used to write characters to a fileFileWriter writer = new FileWriter(“example.txt”);
writer .write(str);
FileReaderSubclass of Reader class and it is used to read characters from a fileFileReader reader = new FileReader(“example.txt”);

int ch; while ((ch = reader.read()) != -1) { System.out.print((char) ch); }
BufferedReaderReads text from a character-input stream, buffering characters for efficient reading.BufferedReader br = new BufferedReader(new FileReader(“input.txt”));
String line; while ((line = br.readLine()) != null) { System.out.println(line); }
BufferedWriterWrites text to a character-output stream, buffering characters for efficient writing.BufferedWriter bw = new BufferedWriter(new FileWriter(“output.txt”));
bw.write(“Hello World!”); bw.newLine(); bw.write(“This is a test.”);
InputStreamReaderConverts bytes from an input stream to characters using a specified charset.FileInputStream fis = new FileInputStream(“input.txt”); InputStreamReader isr = new InputStreamReader(fis, “UTF-8”);
int c;
while ((c = isr.read()) != -1) { System.out.println(c);
}
OutputStreamWriterConverts characters to bytes and writes them to an output stream, using a specified charset.FileOutputStream fos = new FileOutputStream(“output.txt”); OutputStreamWriter osw = new OutputStreamWriter(fos, “UTF-8”); osw.write(“Hello, world!”);
osw.close();
StringReaderReads characters from a string.String inputString = “This is the input string.”;
StringReader reader = new StringReader(inputString);
int c; while ((c = reader.read()) != -1) { System.out.println(c); }
StringWriterStores characters in a string buffer.StringWriter writer = new StringWriter(); writer.write(“Hello, “); writer.write(“world!”); str = writer.toString(); System.out.println(str); writer.close();
CharArrayReaderReads characters from a character array.String str = “Hello, World!”; char[] charArray = str.toCharArray(); CharArrayReader reader = new CharArrayReader(charArray); int ch; while((ch = reader.read()) != -1) { System.out.print((char) ch); }
CharArrayWriterStores characters in a character array.CharArrayWriter writer = new CharArrayWriter();
String str = “Hello, world!”; writer.write(str);
char[] chars = writer.toCharArray();
PipedReaderReads characters from a piped character stream.PipedReader reader = new PipedReader(); PipedWriter writer = new PipedWriter();

writer.connect(reader);

Thread writerThread = new Thread(() -> { try { // Write some data to the PipedWriter for (int i = 0; i < 10; i++) { writer.write(i); } writer.close(); } catch (IOException e) { e.printStackTrace(); } });

writerThread.start();

int data; while ((data = reader.read()) != -1) { System.out.print(data + ” “); } reader.close();
PipedWriterWrites characters to a piped character stream.PipedWriter writer = new PipedWriter();
PipedReader reader = new PipedReader();
writer.connect(reader);

Thread writerThread = new Thread(() -> { try { // Write some data to the PipedWriter for (int i = 0; i < 10; i++) { writer.write(i); } writer.close(); } catch (IOException e) { e.printStackTrace(); } });

writerThread.start();

int data; while ((data = reader.read()) != -1) { System.out.print(data + ” “); } reader.close();

Note – RealTime PipedWriter and PipedReader Example –

PipedReader reader = new PipedReader();
	    PipedWriter writer = new PipedWriter();
	    reader.connect(writer);
	    new Thread(() -> {
	      try {
	        int ch;
	        while ((ch = reader.read()) != -1) {
	          System.out.print((char) ch);
	        }
	      } catch (IOException e) {
	        e.printStackTrace();
	      }
	    }).start();

	    Scanner scanner = new Scanner(System.in);
	    while (scanner.hasNextLine()) {
	      String line = scanner.nextLine();
	      writer.write(line + "\n");
	    }

	    writer.close();

Note – It is advisable to release these resources (calling close() on objects) after usage.

Interview Questions —

  • What is stream in java?
  • What is difference between character stream and byte stream class?

Leave a Reply

Your email address will not be published. Required fields are marked *