java批量复制文件内容

594 阅读1分钟
**实现功能:批量复制指定目录下,指定后缀文件的内容(可以复制目录下的所有文件及子目录下的内容)**
path="D:\\resource"; //源文件夹地址
soutFile="D:\\target.txt"; //目标文件地址
format=".jsp";//指定文件格式
package com.example.demo;import java.io.*;import java.text.Format;/*** @author: mzy* @create: 2020/09/14**/public class demo {static BufferedWriter out = null;static String path="D:\\齐智\\巨感物联智慧消防安全服务云平台 源代码\\xfwlw\\WEB-INF\\views"; //源文件夹地址static String outFile="D:\\齐智\\巨感物联智慧消防安全服务云平台 源代码\\前端代码.txt"; //目标文件地址static String format=".jsp";//指定文件格式public static void main(String[] args) throws IOException {try {getFile(path);} catch (Exception e) {e.printStackTrace();}}public static void getFile(String path) throws Exception {// File对象 可以是文件或者目录File file = new File(path);File[] array = file.listFiles();for (int i = 0; i < array.length; i++) {if (array[i].isFile()) {if (array[i].getName().endsWith( format)) {copy(array[i].getAbsolutePath(),outFile);System.out.println(array[i].getAbsolutePath());System.out.println(array[i].getName());}} else if (array[i].isDirectory()) {getFile(array[i].getPath());}}}public static void copy(String fileName, String filePath) throws Exception {//读取数据(指定编码)String str=fileName;File file =new File(str);String message="";//获取文件内容if(file.isFile() && file.exists()) {BufferedReader br=new BufferedReader(new InputStreamReader(newFileInputStream(file),"utf-8"));String buff;while ((buff=br.readLine()) != null) {message=message+buff+"\n";}br.close();}FileWriter fw = null;try {//如果文件存在,则追加内容;如果文件不存在,则创建文件File f=new File(filePath);fw = new FileWriter(f, true);} catch (IOException e) {e.printStackTrace();}PrintWriter pw = new PrintWriter(fw);pw.println(message);pw.flush();try {fw.flush();pw.close();fw.close();} catch (IOException e) {e.printStackTrace();}}}