Created
May 4, 2025 13:45
-
-
Save hexawulf/33759b65e4272ade04a3bf777f8ab3a6 to your computer and use it in GitHub Desktop.
CompressedFileExample.java - Example for writing and reading compressed text files in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.*; | |
| import java.util.zip.DeflaterOutputStream; | |
| import java.util.zip.InflaterInputStream; | |
| public class CompressedFileExample { | |
| public static void main(String[] args) { | |
| // === COMPRESSED WRITING === | |
| try { | |
| // Step 1: Create a BufferedWriter | |
| // This is the stream the program interacts with directly | |
| BufferedWriter writer = new BufferedWriter( | |
| // Step 2: Convert characters to bytes | |
| new OutputStreamWriter( | |
| // Step 3: Compress the byte stream | |
| new DeflaterOutputStream( | |
| // Step 4: Write bytes to the file | |
| new FileOutputStream( | |
| new File("compressed.txt"))))); | |
| // Write 10 lines of "Hello World!" to the compressed file | |
| for (int i = 0; i < 10; ++i) { | |
| writer.write("Hello World!\n"); | |
| } | |
| writer.close(); // Always close streams to flush and release resources | |
| } catch (FileNotFoundException ex) { | |
| ex.printStackTrace(); | |
| } catch (IOException ex) { | |
| ex.printStackTrace(); | |
| } | |
| // === DECOMPRESSED READING === | |
| try { | |
| // Step 1: Create a BufferedReader | |
| BufferedReader reader = new BufferedReader( | |
| // Step 2: Convert bytes to characters | |
| new InputStreamReader( | |
| // Step 3: Decompress the incoming byte stream | |
| new InflaterInputStream( | |
| // Step 4: Read raw bytes from the file | |
| new FileInputStream( | |
| new File("compressed.txt"))))); | |
| // Read and print all lines until null is returned (end of file) | |
| String line = reader.readLine(); | |
| while (line != null) { | |
| System.out.println(line); | |
| line = reader.readLine(); | |
| } | |
| reader.close(); | |
| } catch (FileNotFoundException ex) { | |
| ex.printStackTrace(); | |
| } catch (IOException ex) { | |
| ex.printStackTrace(); | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
π‘ About This Code
This Java program demonstrates how to store and read compressed text files using a chain of
DataStreams(also called a pipeline).π What It Does
Compressed Writing:
The program creates a file called
compressed.txt, writes "Hello World!" 10 times into it, and compresses the output using the DEFLATE algorithm.Decompressed Reading:
It then reads that same file, decompresses the data, and prints the original lines back to the console.
π§± Stream Pipeline Breakdown
For Writing: