package com.io.datain; import java.io.*; public class TestCopay1 { public static void main(String[] args) throws IOException { File file = new File("D:/Java/20160516-day1"); File file1 = new File("D:/Java/20160516-day102"); copyFileDir(file, file1); } /** * 拷贝目录 * * @param file * @param file1 */ private static void copyFileDir(File file, File file1) { if (file.isDirectory()) { if (!file1.exists()) { file1.mkdirs(); } File[] files = file.listFiles(); for (File item : files) { if (item.isDirectory()) { copyFileDir( new File(file.getAbsolutePath(), item.getName()), new File(file1.getAbsolutePath(), item.getName())); } else { copyFile(new File(file.getAbsolutePath(), item.getName()), new File(file1.getAbsolutePath(), item.getName())); } } } else { copyFile(file, new File(file1.getAbsolutePath() + file.getName())); } } /** * 拷贝文件 * * @param file * @param file1 * @return */ private static boolean copyFile(File file, File file1) { // 创建读取文件的输入流,输出流 // 输入流,对于程序来说,是向程序中输入数据,input FileInputStream fis = null; // 输出流,对于程序来说,是程序向程序外输出数据,output FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(file1); byte[] by = new byte[1024]; int a = 0; a = fis.read(by);// 将读取到的数据放入字节数组by中,并获取放入到字节数组中的字节长度a while (a != -1) { /* 读取多个数据 */ fos.write(by, 0, a);// 将数据写入b文件中 a = fis.read(by);// 继续读取下一次 } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } }