FileUtil.java 6.67 KB
package cn.com.polysoft.utils;

import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件读取工具类
 */
public class FileUtil {

    /**
     * 读取文件内容,作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } 

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        } 

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流  
        FileInputStream fis = new FileInputStream(filePath);  
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];  
        // 用于保存实际读取的字节数  
        int hasRead = 0;  
        while ( (hasRead = fis.read(bbuf)) > 0 ) {  
            sb.append(new String(bbuf, 0, hasRead));  
        }  
        fis.close();  
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }
    /**
     * 保存文件
     * @param path
     * @param fileName
     * @param str
     * @return
     */
    public static boolean saveFile(String path,String fileName,String str){
        boolean flag = true;
        if(!StringUtils.isEmpty(path) && !StringUtils.isEmpty(fileName) && !StringUtils.isEmpty(str)){
            createFileByGBK(path, fileName, str);
            LogUtils.logInfo("---------文件保存成功--------");
        }else{
            flag = false;
            LogUtils.logError("--------文件保存失败--------");
        }
        return flag;
    }

    /**
     *
     * @param path
     * @param fileName
     * @param str
     * @return
     */
    public static boolean saveFile2(String path,String fileName,String str){
        boolean flag = true;
        if(str != null && !str.equals("")){
			String dateDir = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
			path = path + "/" + dateDir + "/";
            try {
                createFileByGBK(path,fileName,str);
            } catch (Exception e) {
                flag = false;
                LogUtils.logInfo("------- 文件保存失败-----------"+e);
            }
        }else{
            flag = false;
            LogUtils.logError("------- 文件信息内容为空-----------");
        }
        return flag;
    }
    /**
     * 以GBK编码存储文件
     *2018年5月7日
     @param path
     @param fileName
     @param str
     */
    private  static void createFileByGBK(String path, String fileName,String str)  {
        StringBuffer sb = new StringBuffer(str);
        try {
            createFile(path,sb, "GBK",fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 写文件到指定目录
     @param path
     @param str
     @param encode
     @param fileName
     */
    public static synchronized void createFile(String path, StringBuffer str, String encode,String fileName)  {
        boolean type = createDir(path);
        if(type == true ){
            BufferedWriter writer = null;
            try {
                FileOutputStream writerStream = new FileOutputStream(path+ "/" + fileName);
                writer = new BufferedWriter(new OutputStreamWriter(writerStream,encode));
                writer.write(str.toString());
                LogUtils.logInfo("------------文件写入完成--------------");
            } catch (Exception e) {
                LogUtils.logError("-------------文件写入失败-------------");
                e.printStackTrace();
            }finally{
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            LogUtils.logInfo("-------------文件路径不存在--------------path:"+path+"---fileName:"+fileName+".xml");
        }
    }
    /**
     * 根据传入path,创建目录
     *2018年5月7日
     @param path
     @return
     */
    private  static boolean createDir(String path) {
        File dir = new File(path);
        if(dir.exists()) {
            LogUtils.logInfo("--------文件夹已经存在---------:");
            return true;
        }else{
            if(!path.endsWith(File.separator))
                path = path + File.separator;
            // 创建单个目录
            if(dir.mkdirs()) {
                LogUtils.logInfo("创建目录:" + path + " 成功!");
                return true;
            } else {
                LogUtils.logInfo("创建目录:" + path + " 失败!");
                return false;
            }
        }
    }
    public static void CopySingleFileTo(String oldPathFile, String targetPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPathFile);
            String targetfile = targetPath ;
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPathFile); //读入原文件
                FileOutputStream fs = new FileOutputStream(targetfile);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    //System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}