ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write("Hello".getBytes()); baos.write("world".getBytes()); byte[] byteArray = baos.toByteArray(); System.out.println(new String(byteArray)); // Output: HelloWorld
try (InputStream inputStream = new FileInputStream("input.txt"); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, length); } String contents = baos.toString(StandardCharsets.UTF_8.name()); System.out.println(contents); // Output: contents of input.txt } catch (IOException e) { e.printStackTrace(); }In this example, we read the contents of a file using FileInputStream and write them into a ByteArrayOutputStream. Then, we convert the buffer into a string using UTF-8 encoding and print it. Finally, we use try-with-resources to automatically close the input stream and output stream objects. The java.io ByteArrayOutputStream class is part of the Java Standard Library.