本文主要是介绍java复制原路径下所有文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
@Test
public void test02() throws FileNotFoundException {
String dirUrl = "D:\\pdf";
String downLoadUrl = "E:\\pdf";
findAllFiles(dirUrl,downLoadUrl);
}
/**
* 保存文件
* @param url :源地址
* @param downLoadUrl: 迁移地址
*/
public void save(String url, String downLoadUrl) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(new File(url));
fos = new FileOutputStream(new File(downLoadUrl));
byte[] bytes = new byte[1024];
int count = 0;
while ((count = fis.read(bytes,0,bytes.length)) != -1){
fos.write(bytes);
fos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 遍历所有数据文件
* @param dirUrl
* @param downLoadUrl
*/
public void findAllFiles(String dirUrl,String downLoadUrl){
File file = new File(dirUrl);
File[] listFiles = file.listFiles();
for (File listFile : listFiles) {
//获取当前目录名称
String listFileName = listFile.getName();
//现在的目录
String newDownLoadUrl = downLoadUrl + "\\" + listFileName;
File fileDown = new File(newDownLoadUrl);
if(listFile.isDirectory()){
//判断目录是否存在
if (!fileDown.exists()){
try {
fileDown.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
findAllFiles(listFile.getAbsolutePath(),newDownLoadUrl);
}else{
System.out.println(fileDown.getAbsolutePath());
save(listFile.getAbsolutePath().toString(),fileDown.getAbsolutePath().toString());
}
}
}
这篇关于java复制原路径下所有文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!