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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay