文件夹的复制

来源:互联网 发布:青少年学习编程的好处 编辑:程序博客网 时间:2024/06/09 23:55
package cn.itcast.iotest;
/*
 * 文件夹的复制
 *   数据源 c:\\demo
 *   数据目的  d:
 * 
 * 操作文件夹 File类 功能
 * 文件的复制 IO流读写文件,字节
 * 
 * 实现思想
 *   1. 数据目的,创建一个和数据源同名文件夹
 *    获取到数据源文件夹名字
 *    File方法mkdirs()
 *    
 *   2. 遍历数据源文件夹的全部文件
 *     listFiles() 获取出的全是文件
 *     
 *   3. 获取数据目的文件名
 *               c:\demo\1.pptx .getName()  1.pptx 
 *    targetDir  d:\\demo  -> d:\demo\1.pptx
 *    数据源的File对象.getNaNe()
 *    用d:\\demo路径,和获取到的文件名组成File对象
 *    new File(File,String)
 *    
 *  4. IO流读写文件
 *  
 *  5. 修改指定的文件名
 *   XXX.txt - > XXX.java
 */
import java.io.*;
public class IOTest2 {
public static void main(String[] args) {
copyDir(new File("c:\\demo"), new File("d:"));
}
/*
* 定义方法,实现文件夹复制
*/
public static void copyDir(File source, File target){
//获取数据源文件夹的名字
String sourceDirName = source.getName();
//在数据目的,创建同名文件夹
//mkdirs()创建的文件夹,是File构造方法封装的路径 d:\\demo
//将目的,获取到的文件夹名,组成一个File对象
File targetDir = new File(target, sourceDirName);
targetDir.mkdirs();
File[] fileNames = source.listFiles();
for(File fileName : fileNames){
//获取数据源的文件名
String sourceFileName = fileName.getName();
//将数据源的文件名和,数据目的的目录组成File对象
File targetFile = new File(targetDir,sourceFileName);
copyFile(fileName,targetFile);
}

//调用一个方法,实现修改文件名的功能
rename(targetDir);

}
/*
* 定义方法,实现修改文件名
* XXX.txt - > XXX.java
* 先把后缀.txt获取出来了
* File类方法 renameTo()
* 数据源File.renameTo(File 数据目的文件名)
*/
public static void rename(File file){
//获取指定文件名
File[] files = file.listFiles(new FileFilter(){
public boolean accept(File pathname){
return pathname.getName().toLowerCase().endsWith(".txt");
}
});
for(File f : files){
System.out.println(f.getName());// d:\demo\1.txt -> d:\demo\1.java
//获取文件名
String filename = f.getName();//1.java.txt substring(0)
int index = filename.lastIndexOf('.');
//System.out.println(index);\
filename = filename.substring(0, index)+".java";
System.out.println(filename);

f.renameTo(new File(file,filename));


}
}



/*
*定义方法,实现IO读写文件 
*字节输入,输出流,构造方法全接收File对象
*/
public static void copyFile(File source,File target){
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
byte[] bytes = new byte[1024];
int len = 0 ;
while((len = fis.read(bytes))!=-1){
fos.write(bytes, 0, len);
}
}catch(IOException ex){
throw new RuntimeException("目的复制失败");
}finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
throw new RuntimeException("释放资源失败");
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException ex) {
throw new RuntimeException("释放资源失败");
}
}
}
}








}
0 0