FileUtil.java對文件做各種處理 保存獲取下載文件 計算文件大小


FileUtil.java對文件做各種處理 保存獲取下載文件 計算文件大小

上傳文件 下載文件 計算文件大小 把文件傳輸到前台
 
package com.beisun.mbp.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

    /**
     * 上傳文件
     * @param filePath 上傳文件目錄
     * @param fileName 保存的文件名稱 
     * @param file 文件流類
     * @param request 請求
     * @throws IOException IO異常
     */
    public static void updoadFile(String filePath,String fileName, MultipartFile file,
            HttpServletRequest request) throws IOException{
        //如果文件夾不存在,則創建文件夾
        File dirPath = new File(filePath);
        if(!dirPath.exists()){
            dirPath.mkdir();   
        }
        
        File uploadFile = new File(dirPath +"/"+ fileName);
        FileCopyUtils.copy(file.getBytes(), uploadFile);    
    }
    
    /**
     * 復制文件
     * @param localFileName 原文件地址和文件名
     * @param tmpFileName 目標文件地址和文件名
     * @throws IOException
     */
    public static void copyFile(String localFileName,String tmpFilePath,String tmpFileName) throws IOException{
        File localFile = new File(localFileName);
        File tmpFile = new File(tmpFilePath,tmpFileName);
        FileCopyUtils.copy(localFile, tmpFile);
    }
    
    /**
     * 刪除文件
     * @param fileName 文件地址和文件名
     * @throws IOException
     */
    public static void deleteFile(String fileName) throws IOException{
        File localFile = new File(fileName);
        localFile.delete();
    }
    
    /**
     * 下載文件,是向頁面輸出流,不返回流
     * @param filePath 文件服務器存儲目錄
     * @param downloadName 下載文件保存的文件名
     * @param fileName 服務器存儲文件名
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @SuppressWarnings("static-access")
    public static void downloadFile(String filePath,String downloadName,String fileName,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
        
        fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
        downloadName = new java.net.URLDecoder().decode(downloadName, "utf-8");
        String path = filePath+fileName;                        
        
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((downloadName).getBytes("GBK"), "iso8859-1"));  
        try {
            //以流的形式下載文件   
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer); 
            toClient.flush();
            toClient.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 獲取文件的is
     * @param filePath 文件服務器存儲目錄
     * @param fileName 服務器存儲文件名
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @SuppressWarnings("static-access")
    public static InputStream getFileIS(String filePath,String fileName,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
        
        fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
        String path = filePath+fileName;                        
        InputStream fis = null;
        try {
            //以流的形式下載文件   
             fis = new BufferedInputStream(new FileInputStream(path));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return fis;
    }
    
    /**
     * 保存文件
     * @param datas    文件數據
     * @param pathName    文件路徑
     */
    public static void saveFile(byte[] datas,String pathName){
        File file = new File(pathName);
    
        //寤虹珛杈撳嚭瀛楄妭嫻�
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            //鐢‵ileOutputStream 鐨剋rite鏂規硶鍐欏叆瀛楄妭鏁扮粍
            fos.write(datas);
            //涓轟簡鑺傜渷IO嫻佺殑寮�攢錛岄渶瑕佸叧闂�
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 獲取文件數據
     * @param pathName    文件路徑
     * @return
     */
    public static byte[] getFile(String pathName){
        File file = new File(pathName);
        byte[] buffer = null;  
        try {  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
            byte[] b = new byte[1000];  
            int n;  
            while ((n = fis.read(b)) != -1) {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return buffer;  

    }
    
    /**
     * 計算文件大小文件大小
     * @param filePath 文件路徑例如:E:\\imgData\\afr\\9211496189393485.jpg
     * @return    文件大小 Kb
     */
    public static long GetFileSize(String filePath){
        long fileSize=0l;
         FileChannel fc= null;  
            try {  
                File f= new File(filePath);  
                if (f.exists() && f.isFile()){  
                    FileInputStream fis= new FileInputStream(f);  
                    fc= fis.getChannel();  
                    fileSize=fc.size()/1024;
                    //logger.info(fileSize); 
                }else{  
                    //logger.info("file doesn't exist or is not a file");  
                }  
            } catch (FileNotFoundException e) {  
                //logger.error(e);  
            } catch (IOException e) {  
                //logger.error(e);  
            } finally {  
                if (null!=fc){  
                    try{  
                        fc.close();  
                    }catch(IOException e){  
                        //logger.error(e);  
                    }  
                }   
            } 
            
            return fileSize;
    }
    
    /**
     * getImage    根據圖片的路徑獲取圖片給前台
     * @author sunjianbo
     * @time 2016年8月25日上午10:41:37
     * @param response
     * @param request
     * @param filePath
     * @throws Exception
     */
    //@RequestMapping(value = "/getImage.do", method = RequestMethod.GET)
    public void getImage(HttpServletResponse response, HttpServletRequest request,String filePath)
            throws Exception {
        
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());
            
            byte[] data = getFile(filePath);
            bos.write(data);
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null)
                bos.close();            
        }
    }
    
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM