Java实现文件或文件夹的复制到指定目录实例
整理文档,搜刮出一个Java实现文件或文件夹的复制到指定目录的代码,稍微整理精简一下做下分享。

10年积累的成都网站制作、做网站经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站策划后付款的网站建设流程,更有磐石免费网站建设让你可以放心的选择与我们合作。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Test {
private static int a = 5;
public static void main(String[] args) {
//需要复制的目标文件或目标文件夹
String pathname = "C:/Users/likun/Desktop/git_project";
File file = new File(pathname);
//复制到的位置
String topathname = "C:/Users/likun/Desktop/movie";
File toFile = new File(topathname);
try {
copy(file, toFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void copy(File file, File toFile) throws Exception {
byte[] b = new byte[1024];
int a;
FileInputStream fis;
FileOutputStream fos;
if (file.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath=filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath=toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());
File copy=new File(toFilepath);
//复制文件夹
if (!copy.exists()) {
copy.mkdir();
}
//遍历文件夹
for (File f : file.listFiles()) {
copy(f, copy);
}
} else {
if (toFile.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath=filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath=toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());
//写文件
File newFile = new File(toFilepath);
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
} else {
//写文件
fis = new FileInputStream(file);
fos = new FileOutputStream(toFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
}
}
}
} 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
网站栏目:Java实现文件或文件夹的复制到指定目录实例
转载源于:http://scpengxi.com/article/jccsig.html
其他资讯
- 关于python之字典的嵌套,递归调用方法-创新互联
- 洛阳抖音代运营哪家好一点
- mysql小于大于怎么写 mysql中的大于号小于号
- Linux查看内存空间的方法(linux查看内存空间)
- 成为完美程序员的10种品质
- 全面认识JVM结构组成
- BCM4323无线网卡在Linux系统下的使用(bcm4323linux)
- 我12月17日在4S店备案买车,第二天4S说备好了,今天4S店打电话说备案退回来了,为什?(网站备案每次提交都被管局说是【退回原因主体负责人有效证件和被)
- Win上也能用Linux命令?下载方法一键get!(linux命令win下载)
- 学习使用lftp命令查看Linux中的文件(linuxlftp查看文件)
