1 package com.outputstream;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 /**
10 * 需求: 拷贝一张图片
11 * @author Administrator
12 *
13 */
14 class Picture{
15 public static void readWrite() throws IOException{
16 //找到原文件
17 File file = new File("D://abc.jpg");
18 //找到存放文件位置
19 File file2 = new File("E://abc.jpg");
20 //建立读取,写入数据通道
21 InputStream inputStream = new FileInputStream(file);
22 FileOutputStream fileOutputStream = new FileOutputStream(file2);
23 //建立缓冲数据,边读边写
24 //每新创建一个FileOutputStream的时候,默认情况下FileOutputStream 的指针是指向了文件的开始的位置。 每写出一次,指向都会出现相应移动。
25 int length = 0;
26 byte[] bs = new byte[1024];
27 while((length = inputStream.read(bs)) != -1){
28 fileOutputStream.write(bs, 0, length);//写出很多次数据,所以就必须要追加。
29 }
30 //关闭资源 原则: 先开后关,后开先关。
31 fileOutputStream.close();
32 inputStream.close();
33 }
34 }
35
36
37 public class Test {
38
39 public static void main(String[] args) throws IOException {
40 // TODO Auto-generated method stub
41
42 Picture picture = new Picture();
43 picture.readWrite();
44 }
45
46 }