标签:
实例01: package cn.itcast05; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; //一次一个字节复制 //一次一个字节数组复制 public class CopyFileDemo01 { public static void main(String[] args) throws IOException { CopyFile2(); } public static void CopyFile() throws IOException { FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("a2.txt"); int c; while((c=fis.read())!=-1) { fos.write(c); } fis.close(); fos.close(); } public static void CopyFile2() throws IOException { FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("a3.txt"); int len; byte[] bytes = new byte[1024]; while((len=fis.read(bytes))!=-1) { fos.write(bytes,0,len); } fis.close(); fos.close(); } }
实例02: package cn.itcast05; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; //一次一个字符复制 //一次一个字符数组复制 public class CopyFileDemo02 { public static void main(String[] args) throws IOException { CopyFile2(); } public static void CopyFile() throws IOException { FileReader fr = new FileReader("a.txt"); FileWriter fw = new FileWriter("a4.txt"); int c; while((c=fr.read())!=-1) { fw.write(c); } fr.close(); fw.close(); } public static void CopyFile2() throws IOException { FileReader fr = new FileReader("a.txt"); FileWriter fw = new FileWriter("a5.txt"); int len; char[] chars = new char[1024]; while((len=fr.read(chars))!=-1) { fw.write(chars, 0, len); } fr.close(); fw.close(); } }
实例03: package cn.itcast05; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; //完成单级文件夹的复制,即: //a文件夹下有多个文件,没有文件夹,将a文件夹中的所有内容,复制到b文件夹中即可。 //建议方法声明: //c //将srcDir文件夹的内容,复制到destDir文件夹中 public class CopyFileDemo03 { public static void main(String[] args) throws IOException { File srcDir = new File("a"); File destDir = new File("b"); copyDir(srcDir, destDir); } public static void copyDir(File srcDir,File destDir) throws IOException { if(!srcDir.exists()) { System.out.println("源文件不存在"); return; } if(!destDir.exists()) { System.out.println("目的文件不存在,需要创建"); destDir.mkdir(); } File[] listFiles = srcDir.listFiles(); for (File file : listFiles) { if(file.isFile()) { String name = file.getName(); copyFile(file, name, destDir); } } } public static void copyFile(File file,String name,File destDir) throws IOException { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(new File(destDir,name)); int len; byte[] bytes = new byte[1024]; while((len=fis.read(bytes))!=-1) { fos.write(bytes,0,len); } fis.close(); fos.close(); } }
标签:
原文地址:http://www.cnblogs.com/qlwang/p/5615630.html