FileTools

package cn.net.zzfz.center.common.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件上传
 * @author song
 *
 */
public class FileTools {
    private static Logger logger = LoggerFactory.getLogger(FileTools.class);
    
    public static void uploadFile(File file, String toFilePath) throws FileNotFoundException, Exception {
        InputStream is = null;
        BufferedOutputStream os = null;
        if(!new File(toFilePath).exists()){
            String path = StringUtils.substringBeforeLast(toFilePath, "/");
            boolean b = new File(path).mkdirs();
            if(!b){
                logger.error("{msg:'上传文件时,创建失败,无权限创建目录, 文件名:[{}]', toFilePath:{}, time:{}}",file.getName(),toFilePath,DateJodaTimeUtils.getNowTime());
                throw new Exception("上传文件时,创建失败,无权限创建目录");
            }
        }
        try {
            is = new FileInputStream(file);
            os = new BufferedOutputStream(new FileOutputStream(toFilePath));
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException fnfe) {
            throw fnfe;
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
        }
    }
        

    public static void uploadFile(InputStream fis, String toFilePath) throws FileNotFoundException, Exception {
        InputStream is = null;
        BufferedOutputStream os = null;
        String path = StringUtils.substringBeforeLast(toFilePath, "/");
        if(!new File(path).exists()){
            boolean b = new File(path).mkdirs();
            if(!b){
                logger.error("{msg:'上传文件时,创建失败,无权限创建目录', toFilePath:{}, time:{}}",toFilePath,DateJodaTimeUtils.getNowTime());
                throw new Exception("上传文件时,创建失败,无权限创建目录");
            }
        }
        
        try {
            is = fis;
            os = new BufferedOutputStream(new FileOutputStream(toFilePath));
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException fnfe) {
            throw fnfe;
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
        }
    }

    public static String getFileContent(String filePath) throws Exception {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(filePath));
            StringBuffer sb = new StringBuffer();
            String temp = null;
            while ((temp = in.readLine()) != null) {
                if (temp.trim().length() > 0) {
                    sb.append(temp).append("\n");
                }
            }
            return sb.toString();
        } finally {
            if (in != null)
                in.close();
        }

    }

    public static List<String> getFileContentList(String filePath) throws Exception {
        BufferedReader in = null;
        List<String> l = new ArrayList<String>();
        try {
            in = new BufferedReader(new FileReader(filePath));
            String temp = null;
            while ((temp = in.readLine()) != null) {
                if (temp.trim().length() > 0) {
                    l.add(temp);
                }
            }
            return l;
        } finally {
            if (in != null)
                in.close();
        }

    }

    public static String getFileContent(File file) throws Exception {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(file));
            StringBuffer sb = new StringBuffer();
            String temp = null;
            while ((temp = in.readLine()) != null) {
                sb.append(temp).append("\r\n");
            }
            return sb.toString();
        } finally {
            if (in != null)
                in.close();
        }
    }
    
    public static String getFileContent(File file, String charset) throws Exception {
        BufferedReader in = null;
        try {
            InputStream is = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(is, charset);
            in = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String temp = null;
            while ((temp = in.readLine()) != null) {
                sb.append(temp).append("\r\n");
            }
            return sb.toString();
        } finally {
            if (in != null)
                in.close();
        }
    }
    
    public static void setFileContent(String content, String filePath) throws Exception {
        FileWriter fw = null;
        try {
            fw = new FileWriter(filePath);
            fw.write(content);
        } finally {
            if (fw != null) {
                fw.close();
            }
        }

    }

    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        return file.delete();
    }

    public static boolean mkdir(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return file.mkdir();
        }
        return true;
    }

    public static boolean mkdirs(String filePath) {
        File file = new File(filePath);
        return file.mkdirs();
    }

    public static void deleteDirectory(File dir) throws IOException {
        if ((dir == null) || !dir.isDirectory()) {
            throw new IllegalArgumentException("Argument " + dir + " is not a directory. ");
        }
        File[] entries = dir.listFiles();
        for (int i = 0; i < entries.length; i++) {
            if (entries[i].isDirectory()) {
                deleteDirectory(entries[i]);
            } else {
                if (!entries[i].delete()) {
                    throw new IllegalArgumentException(entries[i] + " can not be delete. ");
                }
                ;
            }
        }
        if (!dir.delete()) {
            throw new IllegalArgumentException("Argument " + dir + " can not be delete. ");
        }
    }

    public static void buildHtml(String target_url, String save_path) throws FileNotFoundException, IOException {
        try {
            URL openurl = new URL(target_url);
            URLConnection urlConn = openurl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(false);
            urlConn.setUseCaches(false);
            urlConn.connect();
            InputStream is = urlConn.getInputStream();
            BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(save_path));
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            is.close();
            os = null;
            is = null;

        } catch (FileNotFoundException fnfe) {
            throw fnfe;
        } catch (IOException ioe) {
            throw ioe;
        }
    }

    public static String getFileExt(String name) {
        if (name.lastIndexOf(".") == -1) {
            return "";
        }
        return name.substring(name.lastIndexOf(".") + 1, name.length());
    }

    public static String getFileName(String name) {
        if (name.lastIndexOf(".") == -1) {
            return "";
        }
        return name.substring(0, name.lastIndexOf("."));

    }

   
    public static String getRandomFileName(String postfix) {
        java.util.Date dt = new java.util.Date(System.currentTimeMillis());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = fmt.format(dt);
        fileName = fileName + "." + postfix; //extension,   you   can   change   it.
        return fileName;
    }
    
   
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值