Java ByteArrayOutputStreamwrite(int n) 与 ByteArrayOutputStreamwrite(byte[] b, int off, int len) 的区别
时间:2025-01-24
浏览:332
作者:佚名
哈喽!今天心血来潮给大家带来了《Java ByteArrayOutputStreamwrite(int n) 与 ByteArrayOutputStreamwrite(byte[] b, int off, int len) 的区别》,想必大家应该对文章都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习文章,千万别错过这篇文章~希望能帮助到你!
本例演示了如何使用Java从网络URL下载图像数据,并比较了两种不同的write()方法的结果。我们将尝试通过互联网下载图片,并将其保存到本地文件。
方法一:write(byte[] b, int off, int len)
这段代码使用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();
方法二:write(int n)
这段代码使用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())) {
out.write(n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("D:/my-image2.jpg");
fos.write(response);
fos.close();
结果对比
两种方法都成功下载了图片,但生成的my-image1.jpg和my-image2.jpg文件属性存在差异。
![Java ByteArrayOutputStreamwrite(int n) 与 ByteArrayOutputStreamwrite(byte[] b, int off, int len) 的区别](https://img.17golang.com/uploads/20250124/173771753867937722ee3c6.jpg)
观察两个文件的属性,可以发现尺寸存在差异。
![Java ByteArrayOutputStreamwrite(int n) 与 ByteArrayOutputStreamwrite(byte[] b, int off, int len) 的区别](https://img.17golang.com/uploads/20250124/17377175396793772303bd6.jpg)
![Java ByteArrayOutputStreamwrite(int n) 与 ByteArrayOutputStreamwrite(byte[] b, int off, int len) 的区别](https://img.17golang.com/uploads/20250124/1737717539679377230ee5f.jpg)
这说明write(byte[] b, int off, int len)方法效率更高,因为它一次写入多个字节,而write(int n)方法每次只写入一个字节,效率较低,可能导致文件损坏或大小不一致。 建议使用write(byte[] b, int off, int len)方法进行二进制数据的写入。
今天关于《Java ByteArrayOutputStreamwrite(int n) 与 ByteArrayOutputStreamwrite(byte[] b, int off, int len) 的区别》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
