IO普通流复制文件夹和图片

普通字符流只能复制txt文件,不能复制其他格式的文件,因此我们为了实现各种格式都能复制都用字节流来传输

 

为了提高复制速度,后面我们引入了高效流来操作文件,在往后高效IO流随笔中可以看到,本次就只讲普通流

 

照片复制

public static void main(String[] args) throws IOException {
  // 1.创建流对象
  // 1.1 指定数据源
  FileInputStream fis = new FileInputStream("D:\\test.jpg");
  // 1.2 指定目的地
  FileOutputStream fos = new FileOutputStream("test_copy.jpg");
  // 2.读写数据
  // 2.1 定义数组
  byte[] b = new byte[1024];
  int len=-1;
  // 2.3 循环读取,读到没有数据会返回-1就退出循环
  while ((len = fis.read(b))!=‐1) {
  // 2.4 写出数据
  fos.write(b, 0 , len);
  }
  // 3.关闭资源
  fos.close();
  fis.close();
}

 

文件夹的复   public static void main(String[] args) throws Exception {        File file = new File("G:\\22-java\\练习文件");        File desFile = new File("G:\\22-java\\aa");

        findFile(file,desFile);
    }

    public static void findFile(File file,File desFile) throws Exception {
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                String fff=file1.getName();
//                把要移动到的文件夹创建新的文件夹
                File aaa = new File(desFile,fff);
                aaa.mkdirs();
//        如果出现文件夹里面嵌套文件夹,就用递归的方式继续往下查找 findFile(file1,aaa);
} else { String name = file1.getName(); File lastFile = new File(desFile, name);
// 如果它就是个文件不可以再递归就调用复制的方法 copy(file1, lastFile); } } }
public static void copy(File f1, File f2) throws Exception { FileInputStream fIS = new FileInputStream(f1); FileOutputStream fOS = new FileOutputStream(f2); byte[] b = new byte[1024]; int len = -1;
while ((len = fIS.read(b)) != -1) { fOS.write(b, 0, len); } fIS.close(); fOS.close(); }

 

posted @ 2018-08-23 08:19  205李华秋  阅读(367)  评论(0编辑  收藏  举报