复制文件(包含编码设置)

import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

//@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServiceApplication.class)
public class FileTest {

    @Test
    public void copy() throws Exception {
        {
            try {
                //传入两个文件夹路径,其中在Windows中使用的分隔符是"\\"
                copyFile("原路径", "目标路径");
            } catch (Exception ex) {
            }
            System.out.println("Copy File is over!");
        }
    }

    public void copyFile(String source, String destin) throws Exception {
        //原路径
        File path1 = new File(source);
        //要复制到的路径
        File path2 = new File(destin);

        if (path1.exists()) {
            //Create destination folder,如果目标目录不存在,就创建目标目录,因为没有目录文件复制不过去的
            if (!path2.exists()) {
                path2.mkdirs();
            }

            //取得源目录下面的所有文件和文件夹
            File[] items = path1.listFiles();
            OutputStreamWriter fos = null;
            InputStreamReader fis = null;

            //取得所有文件和文件夹之后,遍历处理,如果是文件,就复制文件,如果是文件夹,则递归文件夹下面的文件和文件夹
            for (File item : items) {
                //如果是文件才进行复制
                if (item.isFile()) {
                    //输入输出流的两个常用构造函数,其中在用来了一个字段File.separator,先用输入流读取文件,然后用输出流写文件到目标位置,完成复制功能
                    //若不设置编码,复制HTML文件会乱码
                    fis = new InputStreamReader(new FileInputStream(item), "UTF-8");
                    fos = new OutputStreamWriter(new FileOutputStream(path2 + File.separator + item.getName()), "UTF-8");
                    char[] b = new char[1024];
                    for (int i = 0; (i = fis.read(b)) != -1; ) {
                        fos.write(b, 0, i);
                        fos.flush();
                    }

                    //close the Stream关闭资源啊,什么异常处理的就不写,自己补上吧
                    fos.close();
                    fis.close();

                }
                //如果是文件夹,递归文件夹
                else {
                    copyFile(item.getPath(), destin);
                }
            }
        } else {
            System.out.println("source path:" + source + " is not exists!");
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值