用IO进行文件夹的复制
在经过一段时间的学习,我对于IO的一些认识也逐渐加深。
IO中存在许多的方法,通过对其中一些方法的学习,我才成功地完成了这一次尝试。
接下来就对其中的一些方法简单的说一下自己的理解。
1 ) exists()
方法
exists()
方法是在进行文件的输入输出时经常使用的方法。其功能是查找指定的目录是否存在指定的文件或文件夹,若存在,则返回true
,否则返回false
。
2 ) isFile()
方法
isFile()
方法的作用是判断指定的文件是一个文件还是一个目录,若指定文件存在且为文件时,返回true
,若文件不存在或为目录时,返回false
。
3 ) isDirectory()
方法
isDirectory()
方法的作用是判断指定的文件是一个文件还是一个目录,若指定文件存在且为目录时,返回true
,若文件不存在或为文件时,返回false
。
4 ) mkdirs()
方法
创建此抽象路径名指定的目录,包括创建必需但不存在的父目录。 还有一个mkdir()
方法,此方法只会创建此抽象路径名指定的目录即只能创建一层目录。
5 ) listFiles()
方法
该方法的作用是获取该目录下所有文件和目录的绝对路径。这个方法要与list()
方法区别。list()
方法是获取此目录下的所有文件。
6 ) getAbsolutePath()
方法
用于获取此文件的绝对路径
7 ) substring()
方法
substring()
的作用就是截取父字符串的某一部分来组成新的字符串。该方法有两个重载的方法,分别是
public String substring(int beginIndex)
和public String substring(int beginIndex, int endIndex)
两个方法的作用相同,beginIndex 是开始截取字符串的位置,endIndex 是结束截取字符串的位置。第一个方法是从制度位置开始截取直到字符串末尾,第二个就是从指定位置开始道指定位置结束。
下面就是我进行文件夹的复制的代码
package com.why.filetest.copydir;
import java.io.*;
public class CopyDirTest {
public void copy(File srcFile, File desFile) throws IOException {
if (! srcFile.exists())
System.out.println("文件不存在!");
if(srcFile.isFile()) {
copyFile(srcFile, desFile);
// 利用return返回其本身,使后面的数组可以存储文件数据。
return;
}
File[] files = srcFile.listFiles();
for(File file : files) {
if(file.isDirectory()) {
creatNewDir(desFile, file);
}
copy(file, desFile);
}
}
public void creatNewDir(File desFile, File file) {
String srcPath = file.getAbsolutePath();
String desPath = desFile.getAbsolutePath();
String newPath = (desPath + srcPath.substring(3));
File newFile = new File(newPath);
if(! newFile.exists())
newFile.mkdirs();
}
public void copyFile(File srcFile, File desFile) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
String srcPath = srcFile.getAbsolutePath();
String desPath = desFile.getAbsolutePath();
String newPath = (desPath + srcPath.substring(3));
desFile = new File(newPath);
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(desFile);
byte[] arr = new byte[1024*1024];
while (fis.read(arr) != -1) {
fos.write(arr);
fos.flush();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (fis != null) {
fis.close();
}
if(fos != null) {
fos.close();
}
}
}
public static void main(String[] args) {
CopyDirTest w = new CopyDirTest();
File srcFile = new File("C:\\Users\\why\\code\\Demo\\src\\com\\why\\filetest");
File desFile = new File("E:\\");
try {
w.copy(srcFile, desFile);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
利用上面这段代码,我成功地实现了文件夹的复制。