文件操作類(上傳文件、刪除文件、圖片壓縮、圖片裁剪、文件讀寫...)

package com.lun.util;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * @author zhanglun
 * 本類主要關於文件操作
 * 上傳文件
 * 刪除文件
 * 創建文件夾
 * 判斷路徑是否存在
 * 判斷文件是否是圖片
 * 獲取隨機名字
 * 圖片壓縮
 * 圖片的裁剪
 * 文件的讀與寫
 */
public class FileUtil {
 
 /**
  * 上傳文件
  * @param file 要保存的源文件
  * @param destFile 保存的目標路徑
  */
 public static boolean saveFile(File file,String destFile){
  try {
   destFile = destFile.replaceAll("\\\\", "/");
   if(destFile.lastIndexOf(".")==-1||destFile.lastIndexOf("/")==-1){
    return false;
   }
   //如果不存在該文件夾,就創建
   String tempOutFile=destFile.substring(0,destFile.lastIndexOf("/"));
      if(!new File(tempOutFile).exists()){
       new File(tempOutFile).mkdirs();
      }
     
   //獲得上傳對象的輸入流
   InputStream inputStream = new FileInputStream(file);
  
   if(inputStream != null) {
    //建立文件輸出流
    OutputStream outputStream = new FileOutputStream(destFile);
   
    //建立緩衝區
    byte[] bs = new byte[1024];
    int count = 0;
    //從輸入流中讀出數據放入緩衝區中,並給count賦予寫入緩衝區的總字節數,如果count大於0,就說明還有數據,則繼續寫入。
    while ((count = inputStream.read(bs)) > 0) {
     //將緩衝區數據寫入文件,每次寫入的長度爲count字節
     outputStream.write(bs, 0, count);
    }
    //關閉輸入流
    inputStream.close();
    //關閉文件輸出流
    outputStream.close();
   }
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }
  return true;
 }
 
 /**
  * 生成隨機名字,不可能重複
  */
 public static String getRandomName(){
  Random r=new Random();
  SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
  StringBuffer sb=new StringBuffer();
  sb.append(r.nextInt(100));
  sb.append(r.nextInt(100));
  sb.append("_");
  sb.append(sdf.format(new Date()));
  sb.append("_");
  sb.append(r.nextInt(100));
  sb.append(r.nextInt(100));
  return sb.toString();
 }
 
 /**
  * 創建文件夾
  * @param path 要創建的文件夾路徑
  */
 public static void mkdir(String path){
  if(path == null || path.equals("")){
   return;
  }
  path = path.replaceAll("\\\\", "/");
  int lastIndex = path.lastIndexOf("/");
  if(lastIndex == -1){
   return;
  }
  lastIndex=path.lastIndexOf(".");
  if(lastIndex!=-1){
   path=path.substring(0,path.lastIndexOf("/"));
  }
  File targetPath  = new File(path);
  if(!targetPath.exists()){
   targetPath.mkdirs();
  }
 }
 
 /**
  * 刪除文件
  * @param filePath 要刪除的文件或文件夾路徑
  */
 public static boolean delFile(String filePath){
  if(filePath == null || filePath.equals("")){
   return false;
  }
  try {
   File file = new File(filePath);
   if(file.exists()){
    return file.delete();
   }
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }
  return false;
 }

 

/**
  *用遞歸 刪除文件夾及文件夾下所有的文件
  * @param 要刪除的文件夾路徑
  * @return
  */
 public static boolean delFolder(String folderPath){
  try {
   File file=new File(folderPath);
  
   //如果文件不存在,直接返回
   if(!file.exists()){
    return false;
   }
  
   //如果是具體的文件,而不是文件夾的話,直接刪除
   if(file.isFile()){
    file.delete();
   }
  
   //如果是文件夾
   if(file.isDirectory()){
    String[] fileList=file.list();
    for(int i=0;i<fileList.length;i++){
     String tempStr=folderPath+File.separator+fileList[i];
     File tempFile=new File(tempStr);
     if(tempFile.isFile()){
      tempFile.delete();
     }
    
     //如果是文件夾,用遞歸
     if(tempFile.isDirectory()){
      delFolder(tempStr);
      tempFile.delete();
     }
    }
    file.delete();
   }
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }
  return true;
 }
 
 /**
  * 判斷是否是圖片文件
  * @param args
  */
 public static boolean isImageFile(File file){
  try {
   if(file==null||file.getName()==""){
    return false;
   }
   if(!file.exists()){
    return false;
   }
   BufferedImage image = ImageIO.read(file);
   if(image == null ||image.getWidth() == 0 || image.getHeight() == 0){
    return false;
   }
  } catch (IOException e) {  
   e.printStackTrace();
   return false;
  } 
  return true;
 }
 
 /**
  * 判斷一個文件是否存在
  * @param filePath 文件路徑
  */
 public static boolean existFile(String filePath){
  try {
   if(filePath==null||filePath==""){
    return false;
   }
   File file = new File(filePath);
   return file.exists();
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }
 }
 
 /**  
  * 獲得圖片大小  
  * @param path 圖片路徑  
  */   
   public static long getPicSize(String path) {   
       File file = new File(path);   
       return file.length();   
   }  
 
 /**
  * 根據給定的文件路徑讀取文件內容
  * @param filePath 文件全路徑
  * @return 讀取到的內容
  */
 public static String  read(String filePath){
  if(filePath == null || filePath.isEmpty()){
   return null;
  }
  if(filePath.lastIndexOf(".")==-1){
   return null;
  }
  InputStream is = null;
  try {
   File file = new File(filePath);
   if(!file.exists()){
    return null;
   }
   is = new FileInputStream(file);
   byte buffer[] = new byte[1024];
   int len = 0;
   StringBuffer result = new StringBuffer();
   while((len = is.read(buffer, 0, buffer.length)) > 0){
    result.append(new String(buffer, 0, len));
   }
   return result.toString();
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }finally{
   if(is != null){
    try {
     is.close();
    } catch (IOException e) {
     e.printStackTrace();
     return null;
    }
   }
  }
 }
 
 /**
  * 把內容寫到相應的文件中
  * @param conent 要寫的文件內容
  * @param filePath 文件路徑
  */
 public static boolean write(String content, String filePath){
   if(filePath == null || filePath.isEmpty()){
    return false;
   }
   filePath = filePath.replaceAll("\\\\", "/");
   if(filePath.lastIndexOf(".")==-1||filePath.lastIndexOf("/")==-1){
    return false;
   }
  
   String folder = filePath.substring(0, filePath.lastIndexOf("/"));
   File file = new File(folder);
   if(!file.exists()){
    file.mkdirs();
   }
   BufferedWriter bw = null;
  try {
   bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
   bw.write(content);
   bw.flush();
   return true;
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }finally{
   if(bw != null){
    try {
     bw.close();
    } catch (IOException e) {
     e.printStackTrace();
     return false;
    }
   }
  }
 }
 
 /**
  * 壓縮圖片
  * @param inputFile 源圖片
  * @param outFile 處理後圖片
  * @param width 寬度
  * @param height 高度
  * @param proportion 是否等比縮放
  */
 public static boolean compressPic(String inputFile, String outFile, int width, int height, boolean proportion) {  
  try {   
            //獲得源文件   
           File file = new File(inputFile);   
            if (!file.exists()) {   
               return false;   
            }   
           Image img = ImageIO.read(file);
            // 判斷圖片格式是否正確   
            if (img.getWidth(null) == -1) {  
               return false;   
            } else {   
                int newWidth; int newHeight;   
               // 判斷是否是等比縮放   
                if (proportion == true) {   
                    // 爲等比縮放計算輸出的圖片寬度及高度   
                   double rate1 = ((double) img.getWidth(null)) / (double) width + 0.1;  
                   double rate2 = ((double) img.getHeight(null)) / (double) height + 0.1;  
                    // 根據縮放比率大的進行縮放控制   
                   double rate = rate1 > rate2 ? rate1 : rate2;   
                   newWidth = (int) (((double) img.getWidth(null)) / rate);   
                   newHeight = (int) (((double) img.getHeight(null)) / rate);   
               } else {   
                    newWidth = width; // 輸出的圖片寬度   
                    newHeight = height; // 輸出的圖片高度   
                 }   

               // 如果圖片小於目標圖片的寬和高則不進行轉換
                if(img.getWidth(null) < width  && img.getHeight(null) < height){
                 newWidth = img.getWidth(null);
                 newHeight = img.getHeight(null);
                }
              BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);  
                  
               //Image.SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的,優先級比速度高 生成的圖片質量比較好 但速度慢 
              tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); 
               FileOutputStream out = new FileOutputStream(outFile);  
               // JPEGImageEncoder可適用於其他圖片類型的轉換   
               JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
               encoder.encode(tag);   
               out.close();   
            }   
       } catch (IOException ex) {   
           ex.printStackTrace();   
      }   
        return true;   
    }
 
 /**
  * 裁剪圖片
  * @param srcFile 源圖片
  * @param outFile 產生新圖片路徑
  * @param x x軸的開始座標
  * @param y y軸的開始座標
  * @param width 所裁剪的寬度
  * @param height 所裁剪的高度
  */
public static boolean cutPic(String srcFile,String outFile,int x,int y,int width,int height){
 FileInputStream is = null;
 ImageInputStream iis = null;
 try {
  //如果源圖片不存在
  if(!new File(srcFile).exists()){
   return false;
  }
  
  // 讀取圖片文件
  is = new FileInputStream(srcFile);

  //獲取文件格式
  String ext=srcFile.substring(srcFile.lastIndexOf(".")+1);
  
  //ImageReader聲稱能夠解碼指定格式
  Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(ext);
  ImageReader reader = it.next();
  
  //獲取圖片流
  iis = ImageIO.createImageInputStream(is);

  //輸入源中的圖像將只按順序讀取
  reader.setInput(iis, true);

  //描述如何對流進行解碼
  ImageReadParam param = reader.getDefaultReadParam();

  //圖片裁剪區域
  Rectangle rect = new Rectangle(x, y, width, height);

  //提供一個 BufferedImage,將其用作解碼像素數據的目標
  param.setSourceRegion(rect);

  //使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對象
  BufferedImage bi = reader.read(0, param);

  //保存新圖片
  File tempOutFile=new File(outFile);
  if(!tempOutFile.exists()){
   tempOutFile.mkdirs();
  }
  ImageIO.write(bi, ext, new File(outFile));
  return true;
 } catch (Exception e) {
  e.printStackTrace();
  return false;
 } finally {
  try {
   if (is != null){
    is.close();
   }
   if (iis != null){
    iis.close();
   }
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }
 }
   
}
 
 /**
  * main方法測試
  * @param args
  */
 public static void main(String[] args) {
  System.out.println(FileUtil.compressPic("d:/1.jpg", "d:/2.jpg", 1024, 768, true));
 }
}

 

 

發佈了24 篇原創文章 · 獲贊 14 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章