对文件的操作

Java的文件操作太基础,缺乏很多实用工具,比如对目录的操作,支持就非常的差了。如果你经常用Java操作文件或文件夹,你会觉得反复编写这些代码是令人沮丧的问题,而且要大量用到递归。
    下面是的一个解决方案,借助Apache Commons IO工具包(commons-io-1.1.jar)来简单实现文件(夹)的复制、移动、删除、获取大小等操作。
import org.apache.commons.io.FileUtils; 
import org.apache.commons.io.filefilter.*; 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory;
import java.io.*;
/** 
* 文件工具箱 

* @author leizhimin 2008-12-15 13:59:16 
*/ 
public final class FileToolkit { 
        private static final Log log = LogFactory.getLog(FileToolkit.class);
        /** 
         * 复制文件或者目录,复制前后文件完全一样。 
         * 
         * @param resFilePath 源文件路径 
         * @param distFolder    目标文件夹 
         * @IOException 当操作发生异常时抛出 
         */ 
        public static void copyFile(String resFilePath, String distFolder) throws IOException { 
                File resFile = new File(resFilePath); 
                File distFile = new File(distFolder); 
                if (resFile.isDirectory()) { 
                        FileUtils.copyDirectoryToDirectory(resFile, distFile); 
                } else if (resFile.isFile()) { 
                        FileUtils.copyFileToDirectory(resFile, distFile, true); 
                } 
        }
        /** 
         * 删除一个文件或者目录 
         * 
         * @param targetPath 文件或者目录路径 
         * @IOException 当操作发生异常时抛出 
         */ 
        public static void deleteFile(String targetPath) throws IOException { 
                File targetFile = new File(targetPath); 
                if (targetFile.isDirectory()) { 
                        FileUtils.deleteDirectory(targetFile); 
                } else if (targetFile.isFile()) { 
                        targetFile.delete(); 
                } 
        }
        /** 
         * 移动文件或者目录,移动前后文件完全一样,如果目标文件夹不存在则创建。 
         * 
         * @param resFilePath 源文件路径 
         * @param distFolder    目标文件夹 
         * @IOException 当操作发生异常时抛出 
         */ 
        public static void moveFile(String resFilePath, String distFolder) throws IOException { 
                File resFile = new File(resFilePath); 
                File distFile = new File(distFolder); 
                if (resFile.isDirectory()) { 
                        FileUtils.moveDirectoryToDirectory(resFile, distFile, true); 
                } else if (resFile.isFile()) { 
                        FileUtils.moveFileToDirectory(resFile, distFile, true); 
                } 
        }


        /** 
         * 重命名文件或文件夹 
         * 
         * @param resFilePath 源文件路径 
         * @param newFileName 重命名 
         * @return 操作成功标识 
         */ 
        public static boolean renameFile(String resFilePath, String newFileName) { 
                String newFilePath = StringToolkit.formatPath(StringToolkit.getParentPath(resFilePath) + "/" + newFileName); 
                File resFile = new File(resFilePath); 
                File newFile = new File(newFilePath); 
                return resFile.renameTo(newFile); 
        }
        /** 
         * 读取文件或者目录的大小 
         * 
         * @param distFilePath 目标文件或者文件夹 
         * @return 文件或者目录的大小,如果获取失败,则返回-1 
         */ 
        public static long genFileSize(String distFilePath) { 
                File distFile = new File(distFilePath); 
                if (distFile.isFile()) { 
                        return distFile.length(); 
                } else if (distFile.isDirectory()) { 
                        return FileUtils.sizeOfDirectory(distFile); 
                } 
                return -1L; 
        }
        /** 
         * 判断一个文件是否存在 
         * 
         * @param filePath 文件路径 
         * @return 存在返回true,否则返回false 
         */ 
        public static boolean isExist(String filePath) { 
                return new File(filePath).exists(); 
        }
        /** 
         * 本地某个目录下的文件列表(不递归) 
         * 
         * @param folder ftp上的某个目录 
         * @param suffix 文件的后缀名(比如.mov.xml) 
         * @return 文件名称列表 
         */ 
        public static String[] listFilebySuffix(String folder, String suffix) { 
                IOFileFilter fileFilter1 = new SuffixFileFilter(suffix); 
                IOFileFilter fileFilter2 = new NotFileFilter(DirectoryFileFilter.INSTANCE); 
                FilenameFilter filenameFilter = new AndFileFilter(fileFilter1, fileFilter2); 
                return new File(folder).list(filenameFilter); 

        }

//获得某个目录下所有文件的文件名

File file = new File("E:\\test\\");

File[] files = file.listFiles();

for(int i=0;i<files.length;i++){

if(!files[i].isDirectory()){

files[i];

}

}

        /** 
         * 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!
         * 
         * @param res            原字符串 
         * @param filePath 文件路径 
         * @return 成功标记 
         */ 
        public static boolean string2File(String res, String filePath) { 
                boolean flag = true; 
                BufferedReader bufferedReader = null; 
                BufferedWriter bufferedWriter = null; 
                try { 
                        File distFile = new File(filePath); 
                        if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs(); 
                        bufferedReader = new BufferedReader(new StringReader(res)); 
                        bufferedWriter = new BufferedWriter(new FileWriter(distFile)); 
                        char buf[] = new char[1024];         //字符缓冲区 
                        int len; 
                        while ((len = bufferedReader.read(buf)) != -1) { 
                                bufferedWriter.write(buf, 0, len); 
                        } 
                        bufferedWriter.flush(); 
                        bufferedReader.close(); 
                        bufferedWriter.close(); 
                } catch (IOException e) { 
                        flag = false; 
                        e.printStackTrace(); 
                } 
                return flag; 
        } 


/**
* 解压压缩包到指定文件夹
*/
        private static void unzip(String zipFile, String targetDir) {
  int BUFFER = 4096; //这里缓冲区我们使用4KB,
  String strEntry; //保存每个zip的条目名称
 try {
    BufferedOutputStream dest = null; //缓冲输出流
   FileInputStream fis = new FileInputStream(new File(zipFile));
   ZipInputStream zis = new ZipInputStream(fis);
   ZipEntry entry; //每个zip条目的实例
  while ((entry = zis.getNextEntry()) != null) {
 try {
Log.i("Unzip: ","="+ entry);
      int count; 
      byte data[] = new byte[BUFFER];
      strEntry = entry.getName();
File entryFile = new File(targetDir + "/"+strEntry);
       File entryDir = new File(entryFile.getParent());
      if (!entryDir.isDirectory()) {
      if(entryDir.exists()){
      entryDir.delete();
     }
      entryDir.mkdirs();
      }
      FileOutputStream fos = new FileOutputStream(entryFile);
      dest = new BufferedOutputStream(fos, BUFFER);
      while ((count = zis.read(data, 0, BUFFER)) != -1) {
      dest.write(data, 0, count);
      }
      dest.flush();
      dest.close();
  } catch (Exception ex) {
      ex.printStackTrace();
}
}
       zis.close();
  } catch (Exception cwj) {
    cwj.printStackTrace();

  }

}

/**

*读取文件中的每一行数据

**/

public static void readLine(File file){

BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try {
   reader = new BufferedReader(new FileReader(file));
   String tempString = null;
   int line = 1;
   //一次读入一行,直到读入null为文件结束
   while ((tempString = reader.readLine()) != null){
        System.out.println("当前行的数据是:"+tempString+"\n");
   }
   reader.close();
} catch (IOException e) {
    e.printStackTrace();
} finally {
   if (reader != null){
    try {
    reader.close();
    } catch (IOException e1) {
       }
   }
}

}

/**
* 根据文件路径获取文件内容
* @param fileName
* @return
*/

public static String getContent(String filePath){
File f = new File(filePath);
FileInputStream in = null;
byte[] b = new byte[(int) f.length()];
try {
in = new FileInputStream(f);
in.read(b);
return new String(b, "GB2312");
} catch (Exception e1) {
e1.printStackTrace();
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

}

/**

*重写某个文件

*@Param filePath 要重写的文件路径

*@Param content 要重写的内容

*/

public void rewrite(String filePath,String content){
BufferedWriter bw = null;  
       try {  
           // 根据文件路径创建缓冲输出流  
           bw = new BufferedWriter(new FileWriter(filePath));  
           // 将内容写入文件中  
           bw.write(content);  
       } catch (Exception e) {  
           e.printStackTrace();  
       } finally {  
           // 关闭流  
           if (bw != null) {  
               try {  
                   bw.close();  
               } catch (IOException e) {  
                   bw = null;  
               }  
           }  
       } 
}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值