FileUtil.java 1.48 KB
Newer Older
liqin's avatar
liqin committed
1 2 3 4
package cn.wisenergy.chnmuseum.party.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
liqin's avatar
liqin committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;

public class FileUtil {

	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

	/**
	 * Get the Mime Type from a File
	 * <p>
	 * 参考:http://www.rgagnon.com/javadetails/java-0487.html,http://dada89007.
	 * iteye.com/blog/1392606
	 * </p>
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getMimeType(String fileName) {
		FileNameMap fileNameMap = URLConnection.getFileNameMap();
		String type = fileNameMap.getContentTypeFor(fileName);
		logger.debug("type:" + type);

		return type;
	}

	/**
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytes(String filePath) {
		byte[] buffer = null;
		File file = new File(filePath);
		buffer = getBytes(file);
		return buffer;
	}

	/**
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytes(File file) {
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			buffer = new byte[fis.available()];
			long length = fis.read(buffer);
			fis.close();
			logger.debug("length:" + length);
		} catch (FileNotFoundException e) {
			logger.error("FileNotFoundException异常", e);
		} catch (IOException e) {
			logger.error("IOException异常", e);
		}
		return buffer;
	}

}