FileUtil -工具类 -文件处理类

package cn.com.pubwin.police.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;


/**
 *
 * @author Hongtao.cheng
 * @COMPANY Hintsoft
 * @since 2007-6-28
 */
public class FileUtil {
 public static Logger logger = Logger.getLogger(FileUtil.class);
 private static String resourceFolder = "";

 public static boolean ensureDirectory(File dir) {
  boolean success = true;
  if (dir == null) {
   throw new IllegalArgumentException("dir = null");
  }
  if (!dir.isAbsolute()) {
   dir = new File(dir.getAbsolutePath());
  }
  if (!dir.isDirectory()) {
   success = !dir.isFile() && dir.mkdirs();
   if (!success) {
    try {
     throw new IOException(
       "failed while trying to create directory: "
         + dir.toString());
    } catch (IOException ex) {
     ex.printStackTrace();
    }
   }
  }
  return success;
 }

 public static boolean fileAlreadyExist(String file) {
  return fileAlreadyExist(new File(file));
 }

 public static boolean fileAlreadyExist(File file) {
  return file.exists();
 }

 public static boolean ensureDirectory(String path) {
  return ensureDirectory(new File(path));
 }

 public static void saveStringInFile(File toFile, String insertString)
   throws IOException {
  BufferedWriter out;

  out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
    toFile), "ISO-8859-1"));
  out.write(insertString);
  out.flush();
  out.close();
 }
 
 public static void saveStringInFile(File toFile, String insertString, String enCode) throws IOException {
  BufferedWriter out;

  out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toFile), enCode));
  out.write(insertString);
  out.flush();
  out.close();
 }

 public static String readFileInString(File fromFile) throws IOException {
  StringBuffer strbuf = new StringBuffer((int) fromFile.length());

  BufferedReader in = new BufferedReader(new InputStreamReader(
    new FileInputStream(fromFile), "ISO-8859-1"));
  String str;
  strbuf = new StringBuffer((int) fromFile.length());

  while ((str = in.readLine()) != null) {
   strbuf.append(str + "\n");
  }

  in.close();

  return strbuf.toString();

  /*
   * int lineNumber = 0; byte[] buffer = new byte[1024]; int read;
   * StringBuffer out = new StringBuffer((int)fromFile.length());
   * FileInputStream in = new FileInputStream( fromFile ); read =
   * in.read(buffer); while ( read == 1024 ) { out.append(new
   * String(buffer,"ISO-8859-1")); read = in.read(buffer); }
   * out.append(new String(buffer,0,read,"ISO-8859-1")); in.close();
   * return out.toString();
   */
 }

 public static String readFileInString(File fromFile ,String encode) throws IOException {
  StringBuffer strbuf = new StringBuffer((int) fromFile.length());

  BufferedReader in = new BufferedReader(new InputStreamReader(
    new FileInputStream(fromFile), encode));
  String str;
  strbuf = new StringBuffer((int) fromFile.length());

  while ((str = in.readLine()) != null) {
   strbuf.append(str + "\n");
  }

  in.close();

  return strbuf.toString();

 }
 public static boolean deleteDirectory(String path) {
  return delete(new File(path));
 }

 public static boolean deleteDirectory(File dir) {
  return delete(dir);
 }

 /**
  * Deletes the contents of an existing directory. (May be applied to
  * non-existing files without causing error.)
  *
  * @return <b>true</b> if and only if on termination the directory exists
  *         and is empty
  */
 public static boolean emptyDirectory(File dir) {
  boolean success;

  if (dir == null) {
   throw new IllegalArgumentException("dir = null");
  }

  if ((success = dir.exists() && deleteDirectory(dir))) {
   dir.mkdirs();
  }

  return success && dir.exists();
 }

 /** Delete a single disk file. Function reports errors. */
 public static boolean deleteFile(String path) {
  File f = new File(path);
  return f.delete();
 }

 // deleteFile

 /**
  * General use columba resource InputStream getter.
  *
  * @param path
  *            the full path and filename of the resource requested. If
  *            <code>path</code> begins with "#" it is resolved against the
  *            program's standard resource folder after removing "#"
  * @return an InputStream to read the resource data, or <b>null</b> if the
  *         resource could not be obtained
  * @throws java.io.IOException
  *             if there was an error opening the input stream
  */
 public static InputStream getResourceStream(String path)
   throws java.io.IOException {
  URL url;

  if ((url = getResourceURL(path)) == null) {
   return null;
  } else {
   return url.openStream();
  }
 }

 // getResourceStream

 /**
  * General use columba resource URL getter.
  *
  * @param path
  *            the full path and filename of the resource requested. If
  *            <code>path</code> begins with "#" it is resolved against the
  *            program's standard resource folder after removing "#"
  * @return an URL instance, or <b>null</b> if the resource could not be
  *         obtained
  * @throws java.io.IOException
  *             if there was an error opening the input stream
  */
 public static URL getResourceURL(String path) { // throws
  // java.io.IOException
  URL url;

  if (path == null) {
   throw new IllegalArgumentException("path = null");
  }

  if (path.startsWith("#")) {
   path = resourceFolder + path.substring(1);
  }

  // url = ClassLoader.getSystemResource(path);
  url = FileUtil.class.getResource("/" + path);

  if (url == null) {
   try {
    throw new IOException("*** failed locating resource: " + path);
   } catch (IOException ex) {
    ex.printStackTrace();
   }

   return null;
  }

  return url;
 }

 // getResourceURL

 public static void setResourceRoot(String path) {
  if (path == null) {
   resourceFolder = "";
  } else {
   if (!path.endsWith("/")) {
    path += "/";
   }

   resourceFolder = path;
  }
 }

 // setResourceRoot

 public static String getResourceRoot() {
  return resourceFolder;
 }

 /**
  * Copies the contents of any disk file to the specified output file. The
  * output file will be overridden if it exist. Function reports errors.
  *
  * @param inputFile
  *            a File object
  * @param outputFile
  *            a File object
  * @throws java.io.IOException
  *             if the function could not be completed because of an IO error
  */
 public static void copyFile(File inputFile, File outputFile)
   throws java.io.IOException {
  FileInputStream in = null;
  FileOutputStream out = null;
  if(!inputFile.exists()){
//   logger.error("----------------inputFile:"+inputFile+"不存在!");
   return ;
  }
  boolean ismkdir=false;
  if(!outputFile.getParentFile().exists()){
   logger.error("----------------outputFile:"+outputFile+"不存在!");
   try {
    ismkdir=outputFile.getParentFile().mkdirs();
   } catch (Exception e) {
    logger.error("******outputFile.getParentFile.mkdir:"+ismkdir+":",e);
   }
   
  }
  byte[] buffer = new byte[512];
  int len;

  try {
   out = new FileOutputStream(outputFile);
   in = new FileInputStream(inputFile);

   while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);

   }
  } catch (Exception e) {
   throw new IOException("*** error during file copy is_mkdir:"+ismkdir+" \tinputFile:"+inputFile.getAbsolutePath()+"|||outputFile:"
     + outputFile.getAbsolutePath() + ": " + e.getMessage());
  } finally {
   if (in != null) {
    in.close();
   }
   if (out != null) {
    out.flush();
    out.close();
   }
  }
 }
 // copyFile

 /**
  * Copies a system resource to the specified output file. The output file
  * will be overridden if it exist, so the calling routine has to take care
  * about unwanted deletions of content. Function reports errors.
  *
  * @param resource
  *            a full resource path. If the value begins with "#", it is
  *            resolved against the program's standard resource folder after
  *            removing "#"
  * @return <b>true</b> if and only if the operation was successful,
  *         <b>false</b> if the resource was not found
  * @throws java.io.IOException
  *             if there was an IO error
  */
 public static boolean copyResource(String resource, File outputFile)
   throws java.io.IOException {
  InputStream in = null;
  FileOutputStream out = null;
  byte[] buffer = new byte[512];
  int len;

  // attempt
  try {
   if ((in = FileUtil.getResourceStream(resource)) == null) {
    return false;
   }

   out = new FileOutputStream(outputFile);

   while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
   }
   out.close();
   in.close();
  } catch (IOException e) {
   throw new IOException("*** error during resource file copy "
     + outputFile.getAbsolutePath() + ": " + e.getMessage());
  } finally {
   if (out != null) {
    out.close();
   }
   if (in != null) {
    in.close();
   }
  }
  return true;
 }

 // copyResource

 public static String readStringFromResource(String resource)
   throws java.io.IOException {
  InputStream in;

  byte[] buffer = new byte[512];
  int len;
  StringBuffer result = new StringBuffer();

  // attempt
  try {
   if ((in = FileUtil.getResourceStream(resource)) == null) {
    return "";
   }

   BufferedReader reader = new BufferedReader(
     new InputStreamReader(in));

   String nextLine = reader.readLine();

   while (nextLine != null) {
    result.append(nextLine);
    result.append("\n");
    nextLine = reader.readLine();
   }

   in.close();
  } catch (IOException e) {
   e.printStackTrace();
   throw e;
  }

  return result.toString();
 }

 /**
  * Results equal
  * <code>copyResource ( String resource, new File (outputFile) )</code>.
  */
 public static boolean copyResource(String resource, String outputFile)
   throws java.io.IOException {
  return copyResource(resource, new File(outputFile));
 }

 public static void copyFile(String inputFile, String outputFile)
   throws java.io.IOException {
  copyFile(new File(inputFile), new File(outputFile));
 }

 public static void moveFile(String inputFile, String outputFile)
   throws java.io.IOException {
  copyFile(inputFile, outputFile);
  deleteFile(inputFile);
 }

 public static void renameTo(String inputFile, String outputFile)
   throws java.io.IOException {
  renameTo(new File(inputFile), new File(outputFile));
 }

 public static void renameTo(File inputFile, File outputFile)
   throws java.io.IOException {
  inputFile.renameTo(outputFile);
 }
 public static void directory(String path) {
  File dir = new File(path);
  if (dir.isDirectory()) {
   String[] str = dir.list();
   if (str.length > 0) {
    System.out.println("鐩綍涓嶄负锟??");
   } else {
    deleteDirectory(dir);
   }
  }
 }

 public static boolean delete(File directory) {
  boolean result = false;

  if (directory != null && directory.isDirectory()) {
   File[] files = directory.listFiles();
   for (int i = 0; i < files.length; i++) {
    if (files[i].isDirectory()) {
     delete(files[i]);
    }
    files[i].delete();
   }
   result = directory.delete();
  }
  return result;
 }
 
 /**
  * 向文件中写入内容(会覆盖之前的文件)
  * @param filename 文件路径
  * @param content 内容
  */
 public static void override(String filename, String content) {
  FileOutputStream fileWrite=null;
  try {
   File file = new File(filename);
   
   // 1.1 先保存上传的文件
   if (!file.exists()) {
    file.createNewFile();
   }
   fileWrite = new FileOutputStream(file, false);
   fileWrite.write(content.getBytes());
   fileWrite.close();
  } catch (Exception ex) {
//   ex.printStackTrace();
  }finally{
   if(fileWrite!=null){
    try {
     fileWrite.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }

 }
 
 /**
  * 读取txt文本文档中的内容
  * @param path 文件路径
  * @return String
  */
 public static String readTxt(String path){
  String str="";
  try {
   BufferedReader br=new BufferedReader(new FileReader(path));
   String r=br.readLine();
   while(r!=null){
    str+=r;
    r=br.readLine();
   }
  } catch (FileNotFoundException e) {
  } catch (IOException e) {
  }
  return str;
 }
 
 public static boolean toZipFile(String filePath[], String ftpFilePath  ) throws Exception {
  
  return toZipFile(filePath, new File(ftpFilePath));
 }
 /**
  * 文件的压缩
  * @param filePath filePath 源文件:需要压缩的文件的数组 
  * @param ftpFilePath 目标文件:压缩在ftp的文件目录下面
  * @return
  * @throws IOException
  */
 public static boolean toZipFile(String filePath[], File ftpFilePath  ) throws Exception {
  boolean flag = false;
  ZipOutputStream zip = null;
  InputStream in = null;
  try {
   byte[] b = new byte[1024];
   zip = new ZipOutputStream(new FileOutputStream(ftpFilePath));
   if(filePath != null && filePath.length >0 ){
    for (int i = 0; i < filePath.length; i++) {
     File file = new File(filePath[i]);
     if (!file.exists() || !file.canRead()) {
      continue;
     }
     // 把文件作为一个entry放入zip文件中
     in = new FileInputStream(file);
     
     String fileName = file.getName();
     ZipEntry entry = new ZipEntry(fileName);
     // 把文件对象放入输出流中
     zip.putNextEntry(entry);
     int len = 0;
     while ((len = in.read(b)) != -1) {
      zip.write(b, 0, len);
     }
     in.close();
     zip.closeEntry();// 关闭entry : 关闭当前 ZIP 条目并定位流以写入下一个条目。
    } 
   }
   flag = true;
  } catch ( Exception e) {
   e.printStackTrace();
   flag = false;
  } finally {
   if(null != in){
    in.close();//关闭此输入流并释放与该流关联的所有系统资源。
   }
   if (null != zip) {
    zip.flush();
    zip.close();//关闭此输出流并释放与此流有关的所有系统资源
   }
   
  }
  return flag;
 }
 /**
  * 检查配置文件中的重复项
  * @param file
  */
 public static void checkIsRepeatFile(File file ) {
  String filePath = file.getAbsolutePath();
  checkIsRepeatFile(filePath);
 }
 
 /**
  * 检查配置文件中的重复项
  * @param filePath
  */
 public static void checkIsRepeatFile(String filePath ) {
  List list = (List) getFileRows(filePath);
  checkIsRepeatList(list);
 }
 /**
  * 检查list中的重复项
  * @param list
  */
 public static void checkIsRepeatList(List list) {
  Map repeatMap = new java.util.HashMap();
  
  for (int i = 0; i < list.size() - 1; i++) {
   List list2 = new ArrayList();
   for (int j = list.size() - 1; j > i; j--) {
    if (list.get(j).equals(list.get(i))) {
     list2.add(list.get(j));
     list.remove(j);
    }
   }
   if ((list2.size() + 1) > 1) {
    repeatMap.put(list2.get(0), (list2.size() + 1)+"");
   }
  }
  for( Iterator iter = repeatMap.keySet().iterator();iter.hasNext();){
   String key = (String) iter.next();
   if(repeatMap.get(key) != null && Integer.parseInt((repeatMap.get(key)+"")) >1){
    logger.info("配置项="+key+" ,重复次数="+repeatMap.get(key));
    //System.out.println("配置项="+key+" ,重复次数="+repeatMap.get(key));
   }
  }
  
 }

 public static void writeByte2File(String fileName, byte[] b)
 {
  try {
   FileOutputStream fos = new FileOutputStream(fileName);
   fos.write(b);
   fos.flush();
   fos.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 /**
  * 将文件所有行构建一个Collection
  * @param filename
  * @return
  */
 public static Collection getFileRows(String filename) {
  ArrayList list = new ArrayList();
  File file = new File(filename);
  if(!file.exists()){
   FileUtil.append(filename, "");
  }
  String line = null;
  try {
   BufferedReader bfr = new BufferedReader(new FileReader(file));
   while ((line = bfr.readLine()) != null) {
    if (line.trim().equals("") || line.trim().indexOf("#") != -1) {
     continue;
    }
    //只截取配置名称
    list.add(line.substring(0, line.lastIndexOf("=") != -1 ? line.lastIndexOf("="):line.length()).trim());
   }
   bfr.close();
   return list;
  } catch (Exception ex) {
   return list;
  }
 }
 /**
  * 将content写入filename文件中
  *
  * @param filename
  * @param content
  */
 public static void append(String filename, String content) {
  try {
   File file = new File(filename);
   if (!file.exists()) {
    file.createNewFile();
   }
   FileOutputStream fileWrite = new FileOutputStream(file, true);
   content = content + "\n";
   fileWrite.write(content.getBytes());
   fileWrite.close();

  } catch (Exception ex) {
  }

 }
 /**
  * 将content追加到文件中
  * @param filename
  * @param content
  */
 public static void appendContent2File(String filename, String content) {
  try {
   File file = new File(filename);
   if (!file.exists()) {
    file.createNewFile();
   }
   FileOutputStream fileWrite = new FileOutputStream(file, true);
   content = content + "\n";
   fileWrite.write(content.getBytes());
   fileWrite.close();

  } catch (Exception ex) {
   logger.error("**appendContent2File Exception:"+ex.getMessage(),ex);
  }

 }
 /**
  * 备份/恢复数据
  * @param DbName 数据库名称
  * @param isBackUp :true:备份 ,false:恢复
  * @param to 备份的目的文件 /恢复的目的表
   * @param from 备份/恢复的源数据表
  * @param whereSql 源数据表的过滤条件:where 1=1
  * @param ddlFileName 备份/恢复脚本文件
  * @param isIdentityignore 忽略ID的自增长:true:忽略 ,false:不忽略
  */
 public static boolean backUpOrRestoreData(boolean isBackUp, String DbName,String to,String from ,String whereSql,String ddlFileName,boolean isIdentityignore) throws Exception{
  boolean status = false;
  try {
   //备份:export to ids.FINGER_USER.ixf
   //恢复: import from ids.FINGER_USER.ixf
   if(  fileAlreadyExist(new File(ddlFileName))){
    new File(ddlFileName).delete();
    new File(ddlFileName).createNewFile(); 
    logger.info("**备份/恢复脚本文件:"+ddlFileName+" 文件存在,已重新创建!");
   }else{
    new File(ddlFileName).createNewFile();    
   }
   
   StringBuffer command  = new StringBuffer();
   //连接数据库
   command.append(" su - db2inst <<EON \n");
   command.append("db2 connect to "+DbName+" \n");
   if(isBackUp){
    //备份
    if( fileAlreadyExist(new File(to))){
     new File(to).delete();
     new File(to).createNewFile();
    }else{
     new File(to).createNewFile();
    }
    command.append("db2 \"export to "+to+" of  ixf  select * from "+from+" "+whereSql+" \" \n");
    
    append(ddlFileName, command.toString());
   }else{
    //恢复
    if(!fileAlreadyExist(new File(from))){
     logger.error("**恢复数据报错:"+from+" 文件不存在!");
     return false;
    }
    String  oper = "";//是否忽略ID自增长
    if(isIdentityignore){
     oper = " modified by identityignore ";
    }
    command.append("db2  \"import from "+from+" of ixf "+oper+" insert into "+to+"  \" \n");
    
    append(ddlFileName, command.toString());
   }
   //执行脚本
   /*if(GlobalUtils.checkOperateSystemIsWindows()){
    Runtime.getRuntime().exec("  "+ddlFileName+"");
   }else if(GlobalUtils.checkOperateSystemIsUnixs()){
    
   }*/
   Runtime.getRuntime().exec(" sh "+ddlFileName+"");
   //关闭数据库的连接
   command.append("db2 disconnect to "+DbName+" \n");
   status = true ;
  } catch (Exception e) {
   e.printStackTrace();
   status = false ;
  }
  return status;
  
 }
 
 /**
  * 创建文件
  * @param fileName
  * @return
  * @throws IOException
  */
 public static File  createFile(String fileName) throws IOException{
  //创建文件夹
  File file = new File(fileName);
  if(!file.getParentFile().exists()){
   file.getParentFile().mkdirs();
  }
  file.createNewFile();
  return file;
 }
 /**
  * 创建文件夹
  * @param fileName
  * @return
  * @throws IOException
  */
 public static File  createFileFolder(String fileName) throws IOException{
  //创建文件夹
  File file = new File(fileName);
  if(!file.exists()){
   file.mkdirs();
  }
  return file;
 }
 
 /**
  * 解压ZIP包
  * @param zipPath ZIP源文件目录
  * @param extraPath  ZIP文件解压存放目录
  * @param deleteZip 是否删除ZIP源文件
  */
  public static void extraZip(String zipPath,String extraPath,boolean deleteZip){
         ZipFile zf =null;
         try{
             zf =new ZipFile(zipPath);
             OutputStream output =null;
             InputStream input =null;
             for(Enumeration  entries =(Enumeration )zf.entries();entries.hasMoreElements();){
                 try{
                     ZipEntry entry =(ZipEntry) entries.nextElement();
                     if(entry.isDirectory()){
                         continue;
                     }else{
                         String path =upfilePath(entry.getName());
                         String destPath =extraPath+"/"+path;
                         int loc =destPath.lastIndexOf("/");
                         String destFold =destPath.substring(0,loc+1);
                         File destFoldFile =new File(destFold);
                         String destFileName =destPath.substring(loc+1);
                         File destFileNameFile =new File(destFoldFile,destFileName);
                         if(!destFoldFile.exists())
                             destFoldFile.mkdirs();
                         output=new FileOutputStream(destFileNameFile);
                         input =zf.getInputStream(entry);
                         IOUtils.copy(input, output);
                     }
                 }catch(Exception e){
                     throw new Exception("文件保存出错");
                 }finally{
                     IOUtils.closeQuietly(input);
                     IOUtils.closeQuietly(output);
                 }
             }

         }catch(Exception e){
            e.printStackTrace();
         }finally{
             close(zf);
             if(deleteZip){
                 new File(zipPath).delete();
             }
         }
     }

     public static String upfilePath(String path){
         String upfile="upfile/";
         if(path.startsWith(upfile)){
             return path;
         }else{
             if(path.toLowerCase().startsWith(upfile)){
                 int loc =path.indexOf("/");
                 return upfile+path.substring(loc+1);
             }else{
                 return path;
             }
         }
     }

     public static void close(ZipFile  zf){
            if(null!=zf){
                try{
                    zf.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
     }

 
 
 
 
 public static void main(String[] args) {
   String filePath ="E:\\java -lucene in action\\lucene 资料\\Lucene 博客";
  
   try {
   File file = new File(filePath);
    File[] fs = file.listFiles();
    for (int i = 0; i < fs.length; i++) {
    System.out.println(readFileInString(fs[i],"GBK"));;
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值