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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay