解决问题:将一个文件夹下以.java结尾的文件拷贝到a.txt文件中(源码拷贝)
代码实现:
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;/** * 复制文件夹下以java结尾的文件内容到一个文本文件 * * @author 兴跃神话 * */public class CopyContent { static BufferedWriter fw = null; static{ FileOutputStream fos; //目标文件 File file = new File("D:\\a.txt"); if(!file.exists()){ file.mkdirs(); } try { fos = new FileOutputStream(file); fw = new BufferedWriter(new OutputStreamWriter(fos)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { //源文件所在目录 String filepath = "D:\\Workspaces\\MyeclipceWorkspace\\trainee"; copy(new File(filepath )); fw.close(); System.out.println("复制完成!"); } public static void copy(File file) throws Exception { if (file.isDirectory()) { File[] listFiles = file.listFiles(); for (File file2 : listFiles) { copy(file2); } } if (file.isFile() && file.getName().endsWith(".java")) { fw.newLine(); fw.newLine(); fw.write(file.getName()+"源码:"); fw.newLine(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String str = ""; while ((str = br.readLine()) != null) { fw.write(str); fw.newLine(); } br.close(); } }}