文件操作相关utils

文件操作相关utils

文件操作相关utils

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 文件操作公共类
 */
public class FileUtil {

    /**
     * 删除文件
     * @param filePath
     */
    public static void deleteFile(String filePath) {
        try {
            File fileTemp = new File(filePath);
            if (fileTemp.exists()) {
                fileTemp.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件夹
     * @param dir
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 清空目录下所有文件
     * @param path
     * @return
     */
    public static boolean deleteDir(String path){
        File file = new File(path);
        if(!file.exists()){//判断是否待删除目录是否存在
            System.err.println("The dir are not exists!");
            return false;
        }

        String[] content = file.list();//取得当前目录下所有文件和文件夹
        for(String name : content){
            File temp = new File(path, name);
            if(temp.isDirectory()){//判断是否是目录
                deleteDir(temp.getAbsolutePath());//递归调用,删除目录里的内容
                temp.delete();//删除空目录
            }else{
                if(!temp.delete()){//直接删除文件
                    System.err.println("Failed to delete " + name);
                }
            }
        }
        return true;
    }

    /**
     * 根据url下载图片
     * @param imgurl
     * @return
     */
    public static String downImg(String imgurl) {
        String path = "";
        try {
            URL url = new URL(imgurl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            // 得到输入流
            InputStream inputStream = conn.getInputStream();
            // 获取自己数组
            byte[] getData = readInputStream(inputStream);

            // 文件保存位置
            String dirPath = "C:/logs/demo/img";
            File filedir = new File(dirPath);
            if (!filedir.exists()) {
                filedir.mkdirs();
            }
            path = String.format("%s/%s.jpg", dirPath, StringUtil.getUUID());
            File files = new File(path);
            FileOutputStream fos = new FileOutputStream(files);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    /**
     常用文件的文件头如下:(以前六位为准)
     JPEG (jpg),文件头:FFD8FF
     PNG (png),文件头:89504E47
     GIF (gif),文件头:47494638
     TIFF (tif),文件头:49492A00
     Windows Bitmap (bmp),文件头:424D
     CAD (dwg),文件头:41433130
     Adobe Photoshop (psd),文件头:38425053
     Rich Text Format (rtf),文件头:7B5C727466
     XML (xml),文件头:3C3F786D6C
     HTML (html),文件头:68746D6C3E
     Email [thorough only] (eml),文件头:44656C69766572792D646174653A
     Outlook Express (dbx),文件头:CFAD12FEC5FD746F
     Outlook (pst),文件头:2142444E
     MS Word/Excel (xls.or.doc),文件头:D0CF11E0
     MS Access (mdb),文件头:5374616E64617264204A
     WordPerfect (wpd),文件头:FF575043
     Postscript (eps.or.ps),文件头:252150532D41646F6265
     Adobe Acrobat (pdf),文件头:255044462D312E
     Quicken (qdf),文件头:AC9EBD8F
     Windows Password (pwl),文件头:E3828596
     ZIP Archive (zip),文件头:504B0304
     RAR Archive (rar),文件头:52617221
     Wave (wav),文件头:57415645
     AVI (avi),文件头:41564920
     Real Audio (ram),文件头:2E7261FD
     Real Media (rm),文件头:2E524D46
     MPEG (mpg),文件头:000001BA
     MPEG (mpg),文件头:000001B3
     Quicktime (mov),文件头:6D6F6F76
     Windows Media (asf),文件头:3026B2758E66CF11
     MIDI (mid),文件头:4D546864
     */
    public static String getFileType(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        String fileHead = stringBuilder.toString().toUpperCase();
        if (fileHead.startsWith("FFD8FF")) {
            return "jpg";
        } else if (fileHead.startsWith("89504E")) {
            return "png";
        } else if (fileHead.startsWith("474946")) {
            return "jif";
        } else if (fileHead.startsWith("41564920")) {
            return "avi";
        } else if (fileHead.startsWith("3C3F786D6C")) {
            return "xml";
        } else if (fileHead.startsWith("504B0304")) {
            return "zip";
        } else if (fileHead.startsWith("52617221")) {
            return "rar";
        } else {
            return "data";
        }
    }
}
12-25 08:29