文件操作工具

文件操作工具

zip文件压缩、下载

public class FileUtil {
    
    
    /**
     *生成zip压缩文件
     **/
    public static boolean createCardImgZip(String sourcePath, String zipName) {
    
    
        // TODO Auto-generated method stub
        boolean result = false;
        String zipPath = sourcePath;
        File sourceFile = new File(sourcePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        if (sourceFile.exists() == false) {
    
    
            System.out.println("File catalog:" + sourcePath + "not exist!");
        } else {
    
    
            try {
    
    
                if(!new File(zipPath).exists()){
    
    
                    new File(zipPath).mkdirs();
                }
                File zipFile = new File(zipPath + "/" + zipName + ".zip");
                if (zipFile.exists()) {
    
    
                    System.out.println(zipPath + "Catalog File: " + zipName + ".zip" + "pack file.");
                } else {
    
    
                    File[] sourceFiles = sourceFile.listFiles();
                    if (null == sourceFiles || sourceFiles.length < 1) {
    
    
                        System.out.println("File Catalog:" + sourcePath + "nothing in there,don't hava to compress!");
                    } else {
    
    
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024 * 10];
                        for (int i = 0; i < sourceFiles.length; i++) {
    
    
                            // create .zip and put pictures in
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                            zos.putNextEntry(zipEntry);
                            // read documents and put them in the zip
                            fis = new FileInputStream(sourceFiles[i]);
                            bis = new BufferedInputStream(fis, 1024 * 10);
                            int read = 0;
                            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
    
    
                                zos.write(bufs, 0, read);
                            }
                        }
                        result = true;
                    }
                }
            } catch (FileNotFoundException e) {
    
    
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
    
    
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
    
    
                try {
    
    
                    if(null != bis) {
    
    
                        bis.close();
                    }
                    if(null != zos) {
    
    
                        zos.close();
                    }
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return result;
    }

    public static void doCompress(String srcFile, String zipFile) throws IOException {
    
    
        doCompress(new File(srcFile), new File(zipFile));
    }

    /**
     * 文件压缩
     * @param srcFile 目录或者单个文件
     * @param zipFile 压缩后的ZIP文件
     */
    public static void doCompress(File srcFile, File zipFile) throws IOException {
    
    
        ZipOutputStream out = null;
        try {
    
    
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            doCompress(srcFile, out);
        } catch (Exception e) {
    
    
            throw e;
        } finally {
    
    
            out.close();//记得关闭资源
        }
    }

    public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
    
    
        doCompress(new File(filelName), out);
    }

    public static void doCompress(File file, ZipOutputStream out) throws IOException{
    
    
        doCompress(file, out, "");
    }

    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
    
    
        if ( inFile.isDirectory() ) {
    
    
            File[] files = inFile.listFiles();
            if (files!=null && files.length>0) {
    
    
                for (File file : files) {
    
    
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
    
    
                        name = dir + "/" + name;
                    }
                    FileUtil.doCompress(file, out, name);
                }
            }
        } else {
    
    
            FileUtil.doZip(inFile, out, dir);
        }
    }

    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
    
    
        String entryName = null;
        if (!"".equals(dir)) {
    
    
            entryName = dir + "/" + inFile.getName();
        } else {
    
    
            entryName = inFile.getName();
        }
        ZipEntry entry = new ZipEntry(entryName);
        out.putNextEntry(entry);

        int len = 0 ;
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(inFile);
        while ((len = fis.read(buffer)) > 0) {
    
    
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        fis.close();
    }

}

zip解压到指定目录

ZipFile zipFile;//创建ZipInputStream对象
            zipFile = new ZipFile(mf.getAbsoluteFile());
            Enumeration<? extends ZipEntry > entries = zipFile.entries(); // 获取下一个ZipEntry,获取zipfile里面的每一个zipentry实例
            while (entries.hasMoreElements()){
    
    
                ZipEntry entry=entries.nextElement();
                File entryDestination = new File("D:\\", entry.getName());
                if (entry.isDirectory()) {
    
    
                    entryDestination.mkdirs();
                } else {
    
    
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = zipFile.getInputStream(entry);
                    OutputStream out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    out.close();
                }
            }

文件编码转换

  /** 
   * 把指定文件或目录转换成指定的编码 
   * 
   * @param fileName 
   *      要转换的文件 
   * @param fromCharsetName 
   *      源文件的编码 
   * @param toCharsetName 
   *      要转换的编码 
   * @throws Exception 
   */ 
  public static void convert(String fileName, String fromCharsetName, 
      String toCharsetName) throws Exception {
    
     
    convert(new File(fileName), fromCharsetName, toCharsetName, null); 
  } 
 
  /** 
   * 把指定文件或目录转换成指定的编码 
   * 
   * @param file 
   *      要转换的文件或目录 
   * @param fromCharsetName 
   *      源文件的编码 
   * @param toCharsetName 
   *      要转换的编码 
   * @throws Exception 
   */ 
  public static void convert(File file, String fromCharsetName, 
      String toCharsetName) throws Exception {
    
     
    convert(file, fromCharsetName, toCharsetName, null); 
  } 
 
  /** 
   * 把指定文件或目录转换成指定的编码 
   * 
   * @param file
   *      要转换的文件或目录 
   * @param fromCharsetName 
   *      源文件的编码 
   * @param toCharsetName 
   *      要转换的编码 
   * @param filter 
   *      文件名过滤器 
   * @throws Exception 
   */ 
  public static void convert(String fileName, String fromCharsetName, 
      String toCharsetName, FilenameFilter filter) throws Exception {
    
     
    convert(new File(fileName), fromCharsetName, toCharsetName, filter); 
  } 
 
  /** 
   * 把指定文件或目录转换成指定的编码 
   * 
   * @param file 
   *      要转换的文件或目录 
   * @param fromCharsetName 
   *      源文件的编码 
   * @param toCharsetName 
   *      要转换的编码 
   * @param filter 
   *      文件名过滤器 
   * @throws Exception 
   */ 
  public static void convert(File file, String fromCharsetName, 
      String toCharsetName, FilenameFilter filter) throws Exception {
    
     
    if (file.isDirectory()) {
    
     
      File[] fileList = null; 
      if (filter == null) {
    
     
        fileList = file.listFiles(); 
      } else {
    
     
        fileList = file.listFiles(filter); 
      } 
      for (File f : fileList) {
    
     
        convert(f, fromCharsetName, toCharsetName, filter); 
      } 
    } else {
    
     
      if (filter == null 
          || filter.accept(file.getParentFile(), file.getName())) {
    
     
        String fileContent = getFileContentFromCharset(file, 
            fromCharsetName); 
        saveFile2Charset(file, toCharsetName, fileContent); 
      } 
    } 
  } 
 
  /** 
   * 以指定编码方式读取文件,返回文件内容 
   * 
   * @param file 
   *      要转换的文件 
   * @param fromCharsetName 
   *      源文件的编码 
   * @return 
   * @throws Exception 
   */ 
  public static String getFileContentFromCharset(File file, 
      String fromCharsetName) throws Exception {
    
     
    if (!Charset.isSupported(fromCharsetName)) {
    
     
      throw new UnsupportedCharsetException(fromCharsetName); 
    } 
    InputStream inputStream = new FileInputStream(file); 
    InputStreamReader reader = new InputStreamReader(inputStream, 
        fromCharsetName); 
    char[] chs = new char[(int) file.length()]; 
    reader.read(chs); 
    String str = new String(chs).trim(); 
    reader.close(); 
    return str; 
  } 
 
  /** 
   * 以指定编码方式写文本文件,存在会覆盖 
   * 
   * @param file 
   *      要写入的文件 
   * @param toCharsetName 
   *      要转换的编码 
   * @param content 
   *      文件内容 
   * @throws Exception 
   */ 
  public static void saveFile2Charset(File file, String toCharsetName, 
      String content) throws Exception {
    
     
    if (!Charset.isSupported(toCharsetName)) {
    
     
      throw new UnsupportedCharsetException(toCharsetName); 
    } 
    OutputStream outputStream = new FileOutputStream(file); 
    OutputStreamWriter outWrite = new OutputStreamWriter(outputStream, 
        toCharsetName); 
    outWrite.write(content); 
    outWrite.close(); 
  } 

持续更新…

猜你喜欢

转载自blog.csdn.net/sll714827/article/details/114997719