java后台文件的基本操作


public class FileUtils {
   
   /**
    * 路径分隔符
    */
   public static final char SPT = '/';
   
   /**
    * 创建目录,支持多级
    * 路径之间必须以"/"分隔
    * @param path
    */
   public static void createDir(String path) {
      String[] paths = StringUtils.split(path, SPT);
      StringBuffer sb = new StringBuffer();
      for(String p : paths) {
         sb.append(p);
         sb.append(SPT);
         File dir = new File(sb.toString());
         if(!dir.exists()) {
            dir.mkdir();
         }
      }
   }
   
   public static boolean deleteFile(String path) {
      try {
         if(StringUtils.isEmpty(path) || (path.startsWith("/") && WINDOWS.equals(getOsVersion()))) {
            return false; // 防止在windows下误删文件啊,太恐怖了
         }
         deleteFile(new File(path));
         return true;
      } catch (Exception e) {
         e.printStackTrace();
         return false;
      }
   }

   public static boolean deleteFile(File path) {
      try {
         if (path.isDirectory()) {
            File[] child = path.listFiles();
            if (child != null && child.length != 0) {
               for (int i = 0; i < child.length; i++) {
                  deleteFile(child[i]);
                  child[i].delete();
               }
            }
         }
         path.delete();
         return true;
      } catch (Exception e) {
         e.printStackTrace();
         return false;
      }
   }
   
   public static final String WINDOWS = "windows";
   public static final String LINUX = "linux";
   
   public static String getOsVersion() {
      if ("\\".equals(File.separator)) {
         return WINDOWS;
      } else if ("/".equals(File.separator)) {
         return LINUX;
      } else {
         throw new IllegalAccessError("未知版本系统");
      }
   }

   /**
    * 取得文件夹大小
    * @param realPath
    * @return
    */
   public static long getFileLength(String realPath) {
      try {
         return getFileLength(new File(realPath));
      } catch (Exception e) {
         e.printStackTrace();
      }
      return 0;
   }
   
   /**
    * 取得文件夹大小
    * @param f
    * @return
    * @throws Exception
    */
   public static long getFileLength(File f) throws Exception {
      long size = 0;
      File flist[] = f.listFiles();
      for (int i = 0; i < flist.length; i++) {
         if (flist[i].isDirectory()) {
            size = size + getFileLength(flist[i]);
         } else {
            size = size + flist[i].length();
         }
      }
      return size;
   }
   
   public static long getFileSize(String path) { 
      return getFileSize(new File(path));
   }

   /**
    * 递归求取目录文件个数
    * @param f
    * @return
    */
   public static long getFileSize(File f) {
      long size = 0;
      File flist[] = f.listFiles();
      size = flist.length;
      for (int i = 0; i < flist.length; i++) {
         if (flist[i].isDirectory()) {
            size = size + getFileSize(flist[i]);
            size--;
         }
      }
      return size;

   }
   
   public static String getFileContent(File file) {
      try {
         BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
         StringBuffer buffer = new StringBuffer();
         String text;
         while ((text = input.readLine()) != null) {
            buffer.append(text + "\n"); 
         }
         return buffer.toString();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
      return null;
   }
   
   public static String getFileSizeDesc(long length) {
      if(length < 1024) {
         return length + "B";
      } else if(length < 1024 * 1024) {
         return length / 1024 + "K";
      } else  {
         return length / (1024 * 1024) + "M";
      }
   }
   
   public static String getRandFileName() {
      String name = SgdsStringUtils.longToN36(System.currentTimeMillis());
      return RandomStringUtils.random(4, SgdsStringUtils.N36_CHARS) + name;
   }
   
   public static String getSuffix(String fullName) {
      int idx = fullName.lastIndexOf('.');
      if(idx != -1) {
         return fullName.substring(idx + 1).toLowerCase();
      } else {
         return null;
      }
   }
   
   public static String replaceSpt(String path) {
      return path.replaceAll("\\\\", "/");
   }
   /**
    * 相对路径转绝对地址
    * @param webPath
    * @return
    */
   public static String getRealPath(String webPath,ServletContext application) {
       // super.getCurrentSession().getServletContext().getRealPath(webPath);
        return  application.getRealPath(webPath);
   }
   /**
    * 写文件
    * @param fileName
    * @param content
    */
   public static void appendMethod(String fileName, String content) {
           try {
               //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
               //FileWriter writer = new FileWriter(fileName);
              // writer.write(content);
              // writer.close();
               OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName, false),"UTF-8");
               osw.write(content);
               osw.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
   }
   
   /**
    * @Description: 判断文件是否存在
    * @param filePath
    * @return boolean
    */
   public static boolean isExists(String filePath) {
      if(StringUtils.isNotBlank(filePath)){
         return new File(filePath).exists();
      }
      return false;
   }
   
   /**
    * @Description: 获取文件下面的子文件个数
    * @param filePath
    * @return int
    */
   public static int getSonFileCount(String filePath) {
      if(StringUtils.isNotBlank(filePath)){
         File file= new File(filePath);
         File thumbsFile= new File(filePath +"/Thumbs.db");//如果生成了Thumbs.db文件则把它删除
         if(thumbsFile.exists()){ 
             thumbsFile.delete();
         }
         if(file.exists()){
            return file.listFiles().length;
         }
      }
      return 0;
   }
   
   /**
    * @Description: 将文件拷贝到制定目录
    * @param srcPath
    * @param destDir
    * @throws IOException void
    */
   public static void copyFileToDirectory(String srcPath,String destDir) throws IOException {
      FileUtils.copyFileToDirectory(new File(srcPath), new File(destDir));
   }
}

猜你喜欢

转载自blog.csdn.net/cgt_0812/article/details/80856545