DEV Community

Cover image for Difference Java ByteArrayOutputStream.write(int n) with ByteArrayOutputStream.write(byte[] b, int off, int len)
Maulana Ifandika
Maulana Ifandika

Posted on

Difference Java ByteArrayOutputStream.write(int n) with ByteArrayOutputStream.write(byte[] b, int off, int len)

This function is used to write/enter data from the stream that we are opening, in this case I will try to download image data via the internet with a url. Let's try it.

Code #write(byte[] b, int off, int len)

String val = "https://akcdn.detik.net.id/community/media/visual/2023/03/04/sholat-jenazah_169.jpeg";
URL url = new URL(val);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;

while (-1 != (n=in.read(buf))) {
  out.write(buf, 0, n);
}
out.close();
in.close();

byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("D:/my-image1.jpg");
fos.write(response);
fos.close();
Enter fullscreen mode Exit fullscreen mode

Code #write(int n)

String val = "https://akcdn.detik.net.id/community/media/visual/2023/03/04/sholat-jenazah_169.jpeg";
URL url = new URL(val);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int n = 0;

while (-1 != (n=in.read(buf))) {
  out.write(n);
}
out.close();
in.close();

byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("D:/my-image1.jpg");
fos.write(response);
fos.close();
Enter fullscreen mode Exit fullscreen mode

Result
For the result of image file.

File Image

There are differences when looking at the properties of the two files.

my-image1.jpg
First image file

my-image2.jpg
Second image file

You can see in the size that there is a difference in the size value.

Top comments (0)