Programming Java

Tasks studies - laboratory


Project maintained by dawidolko Hosted on GitHub Pages — Theme by dawidolko

Lab12 - Stream Handling in Java

A stream is a sequence of data, typically bytes. The origin and type of the data sequence depend on the environment. Java provides basic stream types for input and output operations. The InputStream class handles input, while the OutputStream class handles output. Streams are associated with devices such as:

Data types used by streams to transmit information include:

Common Stream Types

Input Streams

  1. AudioInputStream
  2. ByteArrayInputStream
  3. FileInputStream
  4. FilterInputStream
    • BufferedInputStream
    • CheckedInputStream
    • CipherInputStream
    • DataInputStream
    • DigestInputStream
    • InflaterInputStream
    • LineNumberInputStream
    • ProgressMonitorInputStream
    • PushbackInputStream
  5. InputStream
  6. ObjectInputStream
  7. PipedInputStream
  8. SequenceInputStream
  9. StringBufferInputStream

Output Streams

  1. ByteArrayOutputStream
  2. FileOutputStream
  3. FilterOutputStream
    • BufferedOutputStream
    • CheckedOutputStream
    • CipherOutputStream
    • DataOutputStream
    • DeflaterOutputStream
    • DigestOutputStream
    • PrintStream
  4. ObjectOutputStream
  5. OutputStream
  6. PipedOutputStream

Handling Streams in Java

Streams in Java are managed using the InputStream and OutputStream classes, which represent them as sequences of byte elements. Data formatting in streams is often required, which is done using various formatting classes that extend InputStream and OutputStream.

For example, writing text to the console is done using System.out.println(), where out is an object of the PrintStream class that formats byte sequences into text.

Java also includes the Reader and Writer classes for handling text data (String).


Input Handling with InputStream

The InputStream class is abstract and provides methods to read and control bytes from a stream. As an abstract class, its objects cannot be instantiated directly, but they can be obtained through methods like System.in or getInputStream() in the Socket class.

Key methods in InputStream:

Most methods, except markSupported() and mark(), may throw exceptions (e.g., IOException).


Output Handling with OutputStream

The OutputStream class is also abstract, with a key method write() for writing bytes to a stream.

Key methods in OutputStream:

Example: Simple Stream Usage

import java.io.*;

public class Echo {
  public static void main(String args[]) {
    byte b[] = new byte[100];
    try {
      System.in.read(b);
      System.out.write(b);
      System.out.flush();
    } catch (IOException ioe) {
      System.out.println("Input/output error");
    }
  }
}

File Handling

The File class represents abstract file and directory paths. Paths are either relative or absolute, depending on the system.

Examples:

Example:

File file = new File("C:\\data.txt");
File dir = new File("C:\\Documents");
File newFile = new File(dir, "new_file.txt");

Character Streams

Character streams handle Unicode characters (16-bit codes). Classes FileReader and FileWriter are used for reading and writing text files, respectively.

Reading from a Text File

FileReader file = new FileReader("input.txt");
int character;
while ((character = file.read()) != -1) {
  System.out.print((char) character);
}
file.close();

Writing to a Text File

FileWriter file = new FileWriter("output.txt");
file.write("Hello, World!");
file.close();

Buffered Streams

Buffered streams improve efficiency by reading or writing large chunks of data at once.

Example:

import java.io.*;

public class Copy {
  public static void main(String[] args) {
    try {
      FileReader input = new FileReader("input.txt");
      BufferedReader bufferedInput = new BufferedReader(input);
      FileWriter output = new FileWriter("output.txt");
      BufferedWriter bufferedOutput = new BufferedWriter(output);
      String line;
      while ((line = bufferedInput.readLine()) != null) {
        bufferedOutput.write(line);
        bufferedOutput.newLine();
      }
      bufferedInput.close();
      bufferedOutput.close();
    } catch (IOException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
}

Binary Streams

Binary streams handle raw binary data. Classes FileInputStream and FileOutputStream are used for reading and writing binary files.

Reading Binary Files

FileInputStream file = new FileInputStream("input.dat");
int byteData;
while ((byteData = file.read()) != -1) {
  System.out.println(byteData);
}
file.close();

Writing Binary Files

FileOutputStream file = new FileOutputStream("output.dat");
file.write(255); // Writes a single byte
file.close();

Compression Streams

Java provides classes for handling compressed files (e.g., ZIP, GZIP) in the java.util.zip package.

Example: GZIP Compression

import java.io.*;
import java.util.zip.*;

public class Compression {
  public static void main(String[] args) {
    try {
      FileInputStream input = new FileInputStream("input.txt");
      FileOutputStream output = new FileOutputStream("output.gz");
      GZIPOutputStream gzip = new GZIPOutputStream(output);
      byte[] buffer = new byte[1024];
      int bytesRead;
      while ((bytesRead = input.read(buffer)) != -1) {
        gzip.write(buffer, 0, bytesRead);
      }
      input.close();
      gzip.close();
    } catch (IOException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
}

Tasks

  1. Create a program to read a .class file and display the first 20 bytes in hexadecimal format.
  2. Write an application to read a text file line by line and display its contents on the console.
  3. Modify task 2 to prompt for the file name and whether to continue reading another file. Handle exceptions.
  4. Extend the GZIPCompression example to verify reversibility using the CRC32 checksum.
  5. Write a program to copy text files character by character using a method echo(Reader, Writer).
  6. Extend task 5 to measure and display the time taken for copying. Test the effect of buffering on performance.