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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more