FileUtil

package com.bootdo.common.utils;

import java.io.*;

import java.util.UUID;

 

 
import org.bson.types.ObjectId;
 
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import org.weixin4j.misc.BASE64Encoder;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
 
import com.mongodb.DBObject;
 
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;


@Repository
public class FileUtil {
   public static final String FILE_SEPARATOR = System.getProperty("file.separator");

   public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {

      File targetFile = new File(filePath);
      if (!targetFile.exists()) {
         targetFile.mkdirs();
      }
      FileOutputStream out = new FileOutputStream(filePath + fileName);
      out.write(file);
      out.flush();
      out.close();
   }

   public static GridFSInputFile uploadFile(InputStream file, String fileName, MongoTemplate mongoTemplate)
         throws Exception {

      DB db = mongoTemplate.getDb();
      GridFS gridFS = new GridFS(db);

      GridFSInputFile gfs = gridFS.createFile(file);

      gfs.put("filename", fileName);
      gfs.put("contentType", fileName.substring(fileName.lastIndexOf(".")));
      gfs.save();
      return gfs;
      // DBObject query = new BasicDBObject("filename", fileName);
      // GridFSDBFile file1=gridFS.findOne(query);
   }

   // 附件保存到默认集合以外的其他文件存储集合中
   public static GridFSInputFile uploadFile(InputStream file, String fileName, MongoTemplate mongoTemplate,
         String bucket) throws Exception {

      DB db = mongoTemplate.getDb();
      GridFS gridFS = new GridFS(db, bucket);
      GridFSInputFile gfs = gridFS.createFile(file);
      gfs.put("filename", fileName);
      gfs.put("contentType", fileName.substring(fileName.lastIndexOf(".")));
      gfs.save();
      return gfs;
      // DBObject query = new BasicDBObject("filename", fileName);
      // GridFSDBFile file1=gridFS.findOne(query);
   }

   public static GridFSDBFile getFile(String mongid, String bucket, MongoTemplate mongoTemplate) {
      DB db = mongoTemplate.getDb();
      GridFS gridFS = new GridFS(db, bucket);

      DBObject query = new BasicDBObject("_id", new ObjectId(mongid));
      GridFSDBFile file = gridFS.findOne(query);

      return file;
   }

   public static boolean deleteFile(String mongid, String bucket, MongoTemplate mongoTemplate) {

      DB db = mongoTemplate.getDb();
      GridFS gridFS = new GridFS(db, bucket);
      DBObject query = new BasicDBObject("_id", new ObjectId(mongid));
      // GridFSDBFile gridFSDBFile = gridFS.findOne(query);
      gridFS.remove(query);

      return true;
      // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
      // if (file.exists() && file.isFile()) {
      // if (file.delete()) {
      // return true;
      // } else {
      // return false;
      // }
      // } else {
      // return false;
      // }
   }

   public static boolean deleteFile(String fileName) {
      File file = new File(fileName);
      // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
      if (file.exists() && file.isFile()) {
         if (file.delete()) {
            return true;
         } else {
            return false;
         }
      } else {
         return false;
      }
   }

   public static void copy(File srcFile, File destFile) {
      try {
         FileInputStream input = new FileInputStream(srcFile);
         FileOutputStream output = new FileOutputStream(destFile);
         try {
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
               output.write(buffer, 0, n);
            }

         } catch (Exception e) {
            e.printStackTrace();
         } finally {
            if (output != null) {
               output.close();
            }
            if (input != null) {
               input.close();
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static String renameToUUID(String fileName) {
      return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
   }

   /**
    * 获得预览文件
    * 
    * @param mongid
    * @param bucket
    * @param mongoTemplate
    * @return
    */
   public static GridFSDBFile getFileInPreviewByMd5Id(String md5id, MongoTemplate mongoTemplate) {
      DB db = mongoTemplate.getDb();
      GridFS gridFS = new GridFS(db, "preview");
      DBObject query = new BasicDBObject("filemd5", md5id);
      GridFSDBFile file = gridFS.findOne(query);
      return file;
   }

   /**
    * 根据md5id删除用于预览的zip文件
    * 
    * @param mongid
    * @param bucket
    * @param mongoTemplate
    * @return
    */
   public static boolean deletePreviewByMd5Id(String MD5id, MongoTemplate mongoTemplate) {
      String bucket = "preview";
      DB db = mongoTemplate.getDb();
      GridFS gridFS = new GridFS(db, bucket);
      DBObject query = new BasicDBObject("filemd5", MD5id);
      gridFS.remove(query);
      return true;
   }

   /**
    * 根据String创建文件路径
    * 
    * @param destDirName
    * @return
    */
   public static boolean createDir(String destDirName) {
      File dir = new File(destDirName);
      if (dir.exists()) {
         return false;
      }
      if (!destDirName.endsWith(File.separator)) {
         destDirName = destDirName + File.separator;
      }
      if (dir.mkdirs()) {
         return true;
      } else {
         return false;
      }
   }

   public static boolean deleteLocalZipFileByDir(String dir) {

      return true;
   }

   /**
    * 递归删除目录下的所有文件及子目录下所有文件
    * 
    * @param dir
    *            将要删除的文件目录
    * @return
    */
   public static boolean deleteDir(File dir) {
      System.gc();
      if (dir.isDirectory()) {
         String[] children = dir.list();
         // 递归删除目录中的子目录下
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
               return false;
            }
         }
      }
      // 目录此时为空,可以删除
      return dir.delete();
   }
 
   /**
    * 将文件转成base64 字符串
    * 
    * @param path文件路径
    * @return *
    * @throws Exception
    */
   public static String encodeBase64File(File file) throws Exception {
      FileInputStream inputFile = new FileInputStream(file);
      byte[] buffer = new byte[(int) file.length()];
      inputFile.read(buffer);
      inputFile.close();
      String s = new BASE64Encoder().encode(buffer);
      return s;
   }

   public static String encodeBase64File1(File file) throws Exception {
      FileInputStream inputFile = new FileInputStream(file);
      byte[] buffer = new byte[(int) file.length()];
      inputFile.read(buffer);
      inputFile.close();
      String s = new BASE64Encoder().encode(buffer);
      return s;
   }
   
   public static String getRealFilePath(String path) {  
        return path.replace("/", FILE_SEPARATOR).replace("\\", FILE_SEPARATOR);  
    }

   /**
    * 输入流转字节流
    * */
   public static byte[] InputStreamToByte(InputStream is) throws IOException {
      ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
      byte[] buffer=new byte[1024];
      int ch;
      while ((ch = is.read(buffer)) != -1) {
         bytestream.write(buffer,0,ch);
      }
      byte data[] = bytestream.toByteArray();
      bytestream.close();
      return data;
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值