通过Java的OutputStream和InputStream实现图片的复制功能。
步骤如下:
- 定义FileInputStream对象来读取图片
- 定义FileOutputStream对象来写入图片
- 调用FileInputStream对象的read函数来读字节
- 调用FileOutputStream对象的write函数写字节
- 关闭输入流和输出流
完整代码如下:
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 ((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();
}
}
}
}
纸上得来终觉浅,绝知此事要躬行。开发这条路只有自己动手才能有所突破,看一百遍不如动手敲一遍。加油,小伙伴~
|