您的位置:首页 > 编程语言 > Java开发

JAVA文件操作示例

2008-03-18 13:35 483 查看
/**
 *级连删除文件夹或文件
 *by lecky.lee
 *2006-06-07
 */
package com.lecky;

import java.io.*;


public class delete
{

 public static void main(String[] args) throws IOException
 {
 delete del = new delete();

 del.deleteFiles("c:/CourseManage");
 System.out.println ("删除完毕");
 }
 //删除文件及文件夹方法
 public void deleteFiles(String path){
 File f = new File(path);
 if(!f.exists()){
 System.out.println ("文件不存在");
 System.exit(5);
 }
 if(f.isFile()){
 this.deleteFile(f);
 }
 else{
 this.deleteDir(f);
 }
 }
 //删除文件夹
 public void deleteDir(File f){
 System.out.println(f.getPath());
 File temp[]=f.listFiles();
 for(int i=0;i this.deleteFiles(temp[i].toString());
 //递归调用此方法
 }
 f.delete();
 }
 //删除单个文件
 public void deleteFile(File f){
 System.out.println(f.getPath());
 f.delete();

 }


}
--------------------------------------

package ce.lecky;

import java.io.*;
import java.util.*;
/**
*复制文件
*by lecky.lee
*2006-06-08
*/

public class CopyFile
{
 String intiPathOut;
 //初始输出路径
 int cnt=0;
 //计数器,用于判定是否首次调用copyFiles方法
 public void copyFiles(String pathIn,String pathOut) throws IOException
 {
 File f= new File(pathIn);
 if(!f.exists()){
 System.out.println ("源文件路径不存在");
 System.exit(5);
 }
 if(cnt==0){
 File out = new File(this.intiPathOut);
 out.mkdir();
 //首次调用执行,创建初始输出目录
 }
 if(f.isFile()){
 this.copyFile(f,pathOut);
 }
 else{
 this.copyDir(f,pathOut);
 }

 cnt++;

 }

 public void copyDir(File f,String pathOut) throws IOException{
 System.out.println(f.getPath());


 pathOut=this.intiPathOut+f.getPath().substring(2);
 //修改输出路径字符串,将子文件夹相对路径追加至初始输出路径
 //substring用于去掉路径中的驱动器盘符
 File dir = new File(pathOut);
 dir.mkdir();


 File temp[]=f.listFiles();
 for(int i=0;i this.copyFiles(temp[i].toString(),pathOut);
 //递归调用此方法
 }

 }

 public void copyFile(File f,String pathOut) throws IOException{
 System.out.println(f.getPath());

 DataInputStream in = new DataInputStream(
 new BufferedInputStream(
 new FileInputStream(f.getPath())));


 byte[] date = new byte[in.available()];

 in.read(date);

 DataOutputStream out = new DataOutputStream(
 new BufferedOutputStream(
 new FileOutputStream(pathOut+"/"+f.getName())));


 out.write(date);

 in.close();
 out.close();

 }
 public static void main(String[] args) throws IOException
 {
 CopyFile cp = new CopyFile();
 cp.intiPathOut="D:/11111111";
 cp.copyFiles("D:/lecky","D:/11111111");
 System.out.println ("复制完毕");
 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: