import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; public class Example { public static void main(String[] args) throws IOException { // input string to compress String input = "Hello, world!"; // create a ByteArrayOutputStream to hold compressed data ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); // create a GZIPOutputStream to compress the data and write to the byte stream try (GZIPOutputStream gzipStream = new GZIPOutputStream(byteStream)) { gzipStream.write(input.getBytes()); } // get the compressed data as a byte array byte[] compressedData = byteStream.toByteArray(); // write the compressed data to a file try (OutputStream fileStream = new FileOutputStream("compressed.txt")) { fileStream.write(compressedData); } } }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; public class Example implements Serializable { private static final long serialVersionUID = 1L; private int number; private String text; public Example(int number, String text) { this.number = number; this.text = text; } public static void main(String[] args) throws IOException { // create an instance of the Example class to serialize Example example = new Example(42, "Hello, world!"); // create a ByteArrayOutputStream to hold the serialized data ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); // create an ObjectOutputStream to serialize the object and write to the byte stream try (ObjectOutputStream objectStream = new ObjectOutputStream(byteStream)) { objectStream.writeObject(example); } // get the serialized data as a byte array byte[] serializedData = byteStream.toByteArray(); System.out.println("Serialized data:"); for (byte b : serializedData) { System.out.print(b + " "); } } }In both examples, the ByteArrayOutputStream is closed implicitly when the try-with-resources block ends. If you need to manually close the byte stream, you can call the close() method on the ByteArrayOutputStream object.