File operations related utils

File operations related 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 = newFile (filePath);
             IF (fileTemp.exists ()) { 
                fileTemp.delete (); 
            } 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 
    } 
    
    / ** 
     * delete folders 
     * @param the dir 
     * @return  
     * / 
    public  static  Boolean DeleteDir (File the dir) {
         IF (dir.isDirectory ()) { 
            String [] Children = dir.list ();
             // recursive directory delete subdirectories 
            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 ()) { // determines whether to delete the directory exists 
            System.err.println ( "Not are the dir of The EXISTS!" );
             return  to false ; 
        } 
        
        String [] Content = File.List for (); / / get all the files and folders in the current directory 
        for (String name: Content) { 
            file the TEMP = new new file (path, name);
             iF (temp.isDirectory ()) { // determine whether the directory 
                deleteDir (temp.getAbsolutePath ( )); // recursive call, delete the contents of the directory 
                temp.delete (); // delete empty directories 
            } the else {
                IF (! temp.delete ()) { // delete files 
                    System.err.println ( "Failed to the Delete" + name); 
                } 
            } 
        } 
        return  to true ; 
    } 
    
    / ** 
     * According url download pictures 
     * @param imgUrl 
     * @return 
     * / 
    public  static String downImg (String imgUrl) { 
        String path = "" ;
         the try { 
            the URL URL = new new the URL (imgUrl); 
            the HttpURLConnection Conn =(The HttpURLConnection) url.openConnection ();
             // set over time is 3 seconds 
            conn.setConnectTimeout (1000 *. 3 );
             // prevented from crawling shield 403 returns an error 
            conn.setRequestProperty ( "User-Agent", "Mozilla / 4.0 (compatible; MSIE 5.0; Windows NT; DigExt) " ); 
            
            // get the input stream 
            InputStream inputStream = conn.getInputStream ();
             // get your own array 
            byte [] getData = readInputStream (inputStream); 
            
            // file location 
            String = dirpath "C: / logs / Demo / IMG" ; 
            File filedir = new 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 (); 
    } 


    / ** 
     Common Files head follows :( previous six prevail) 
     JPEG (JPG), header: FFD8FF 
     PNG (PNG), the file header: 89504E47 
     GIF (GIF), the file header: 47,494,638 
     TIFF (TIF), the file header: 49492A00 
     Windows Bitmap (BMP ), header: 424D 
     CAD (DWG), the file header: 41.43313 million 
     Adobe Photoshop (PSD), the file header: 38,425,053 
     Rich Text the Format (RTF), the file header: 7B5C727466 
     XML (xml), header: 3C3F786D6C 
     HTML (HTML), header: 68746D6C3E  
     Email [Thorough only] (EML), the file header: 44656C69766572792D646174653A
     Outlook Express (dbx), header: CFAD12FEC5FD746F
     Outlook (pst), the file header: 2142444E 
     the MS Word / Excel (xls.or.doc), the file header: D0CF11E0 
     the MS Access (MDB), the file header: 5374616E64617264204A 
     the WordPerfect (wpd), the file header: FF575043 
     the Postscript (eps.or. ps), header: 252150532D41646F6265 
     Adobe Acrobat (pdf), the file header: 255044462D312E 
     Quicken (QDF), header: AC9EBD8F 
     Windows Password (PWL), header: E3828596 
     ZIP Archive (ZIP), the file header: 504B0304 
     RAR Archive (RAR ), header: 52,617,221 
     Wave (WAV), header: 57,415,645 
     AVI (AVI), header: 41.56492 million 
     Real Audio (RAM), the file header: 2E7261FD 
     Real Media (RM), header: 2E524D46 
     MPEG (MPG), file head: 000001BA  
     the MPEG (MPG), the file header: 000001B3
     Quicktime (mov), header: 6D6F6F76 
     Windows Media (asf), header: 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";
        }
    }
}

Guess you like

Origin www.cnblogs.com/wangquanyi/p/12106862.html