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!");
}
}
}
复制文件(包含编码设置)
最新推荐文章于 2022-12-15 20:26:19 发布