Java 实现复制图片

通过Java的OutputStream和InputStream实现图片的复制功能。

步骤如下:

  • 定义FileInputStream对象来读取图片
  • 定义FileOutputStream对象来写入图片
  • 调用FileInputStream对象的read函数来读字节
  • 调用FileOutputStream对象的write函数写字节
  • 关闭输入流和输出流

完整代码如下:

/*** Author:wangbl* Date:2022/2/8* Time:13:45* Description:使用字节流实现复制图片功能**/
public class CopyPicture {public static void main(String[] args) {//图片资源FileInputStream fileInputStream = null;//需要粘贴的图片资源FileOutputStream fileOutputStream = null;try {fileInputStream = new FileInputStream("a.jpg");fileOutputStream = new FileOutputStream("b.jpg");//定义一个字节数组,用来充当缓存区byte[] bytes = new byte[1024];int length = 0;//通过while循环将读取的字节写入到字节数组中,如果== -1则表示已经读取完毕while ((length = fileInputStream.read(bytes)) != -1){//将字节数组写入文件fileOutputStream.write(bytes,0,length);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {//关闭输入流和输出流try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}
}

纸上得来终觉浅,绝知此事要躬行。开发这条路只有自己动手才能有所突破,看一百遍不如动手敲一遍。加油,小伙伴~


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部