示例代码:
import java.io.*; public class Test05 { public static void main(String[] args) { //复制单级目录中的所有文件内容 File file = new File("d:\\aa");//源文件 File file2 = new File("aa");//目标文件 file2.mkdir();//创建单级目录 File[] files = file.listFiles();//文件集合 String[] list = file.list();//文件名集合 for (int i = 0; i < files.length; i++) {//遍历集合 if (files[i].isFile()) {//如果是文件 File f2 = new File(file2, list[i]);//创建名字一样的文件 try { f2.createNewFile();//创建一个新文件 //复制文件中的内容 try (Reader in = new FileReader(files[i]); Writer out = new FileWriter(f2)) { //创建字符数组 char[] ch = new char[1024 * 1024]; int len =0; while ((len = in.read(ch)) != -1) { out.write(ch,0,len);//将读取到的内容写入目标文件中 } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } System.out.println("文件复制完毕"); } }