import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class Example1 { public static void main(String[] args) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write("Example content".getBytes()); //write the contents of byte array to file FileOutputStream fileOutputStream = new FileOutputStream("output.txt"); byteArrayOutputStream.writeTo(fileOutputStream); fileOutputStream.close(); } }
import java.io.ByteArrayOutputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; public class Example2 { public static void main(String[] args) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write("Example content".getBytes()); //compress the contents using GZIP format GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream); gzipOutputStream.finish(); //compress the contents using DEFLATE format DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream); deflaterOutputStream.finish(); } }This example creates a ByteArrayOutputStream object and writes the string "Example content". It then uses the GZIPOutputStream and DeflaterOutputStream classes to compress the contents of the output stream using GZIP and DEFLATE formats, respectively. The java.io package provides classes to handle input and output operations. The ByteArrayOutputStream class is one of the classes in this package.