Commit 3ad32322 authored by 张永's avatar 张永

加个方法

parent 5b04f123
package com.egolm.common; package com.egolm.common;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.io.Writer; import java.io.Writer;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.ImageReader; import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import com.egolm.common.exception.FileUtilException; import com.egolm.common.exception.FileUtilException;
public class FileUtil { public class FileUtil {
private final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>(); private final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
static { static {
FILE_TYPE_MAP.put("AMR", "2321414D520A"); FILE_TYPE_MAP.put("AMR", "2321414D520A");
FILE_TYPE_MAP.put("JPG", "FFD8FF"); // JPEG (jpg) FILE_TYPE_MAP.put("JPG", "FFD8FF"); // JPEG (jpg)
FILE_TYPE_MAP.put("PNG", "89504E47"); // PNG (png) FILE_TYPE_MAP.put("PNG", "89504E47"); // PNG (png)
FILE_TYPE_MAP.put("GIF", "47494638"); // GIF (gif) FILE_TYPE_MAP.put("GIF", "47494638"); // GIF (gif)
FILE_TYPE_MAP.put("TIF", "49492A00"); // TIFF (tif) FILE_TYPE_MAP.put("TIF", "49492A00"); // TIFF (tif)
FILE_TYPE_MAP.put("BMP", "424D"); // Windows Bitmap (bmp) FILE_TYPE_MAP.put("BMP", "424D"); // Windows Bitmap (bmp)
FILE_TYPE_MAP.put("DWG", "41433130"); // CAD (dwg) FILE_TYPE_MAP.put("DWG", "41433130"); // CAD (dwg)
FILE_TYPE_MAP.put("HTML", "68746D6C3E"); // HTML (html) FILE_TYPE_MAP.put("HTML", "68746D6C3E"); // HTML (html)
FILE_TYPE_MAP.put("RTF", "7B5C727466"); // Rich Text Format (rtf) FILE_TYPE_MAP.put("RTF", "7B5C727466"); // Rich Text Format (rtf)
FILE_TYPE_MAP.put("XML", "3C3F786D6C"); FILE_TYPE_MAP.put("XML", "3C3F786D6C");
FILE_TYPE_MAP.put("ZIP", "504B0304"); FILE_TYPE_MAP.put("ZIP", "504B0304");
FILE_TYPE_MAP.put("RAR", "52617221"); FILE_TYPE_MAP.put("RAR", "52617221");
FILE_TYPE_MAP.put("PSD", "38425053"); // Photoshop (psd) FILE_TYPE_MAP.put("PSD", "38425053"); // Photoshop (psd)
FILE_TYPE_MAP.put("EML", "44656C69766572792D646174653A"); // Email (eml) FILE_TYPE_MAP.put("EML", "44656C69766572792D646174653A"); // Email (eml)
FILE_TYPE_MAP.put("DBX", "CFAD12FEC5FD746F"); // Outlook Express (dbx) FILE_TYPE_MAP.put("DBX", "CFAD12FEC5FD746F"); // Outlook Express (dbx)
FILE_TYPE_MAP.put("PST", "2142444E"); // Outlook (pst) FILE_TYPE_MAP.put("PST", "2142444E"); // Outlook (pst)
FILE_TYPE_MAP.put("XLS", "D0CF11E0"); // MS Word FILE_TYPE_MAP.put("XLS", "D0CF11E0"); // MS Word
FILE_TYPE_MAP.put("DOC", "D0CF11E0"); // MS Excel 注意:word 和 excel的文件头一样 FILE_TYPE_MAP.put("DOC", "D0CF11E0"); // MS Excel 注意:word 和 excel的文件头一样
FILE_TYPE_MAP.put("MDB", "5374616E64617264204A"); // MS Access (mdb) FILE_TYPE_MAP.put("MDB", "5374616E64617264204A"); // MS Access (mdb)
FILE_TYPE_MAP.put("WPD", "FF575043"); // WordPerfect (wpd) FILE_TYPE_MAP.put("WPD", "FF575043"); // WordPerfect (wpd)
FILE_TYPE_MAP.put("EPS", "252150532D41646F6265"); FILE_TYPE_MAP.put("EPS", "252150532D41646F6265");
FILE_TYPE_MAP.put("PS", "252150532D41646F6265"); FILE_TYPE_MAP.put("PS", "252150532D41646F6265");
FILE_TYPE_MAP.put("PDF", "255044462D312E"); // Adobe Acrobat (pdf) FILE_TYPE_MAP.put("PDF", "255044462D312E"); // Adobe Acrobat (pdf)
FILE_TYPE_MAP.put("QDF", "AC9EBD8F"); // Quicken (qdf) FILE_TYPE_MAP.put("QDF", "AC9EBD8F"); // Quicken (qdf)
FILE_TYPE_MAP.put("PWL", "E3828596"); // Windows Password (pwl) FILE_TYPE_MAP.put("PWL", "E3828596"); // Windows Password (pwl)
FILE_TYPE_MAP.put("WAV", "57415645"); // Wave (wav) FILE_TYPE_MAP.put("WAV", "57415645"); // Wave (wav)
FILE_TYPE_MAP.put("AVI", "41564920"); FILE_TYPE_MAP.put("AVI", "41564920");
FILE_TYPE_MAP.put("RAM", "2E7261FD"); // Real Audio (ram) FILE_TYPE_MAP.put("RAM", "2E7261FD"); // Real Audio (ram)
FILE_TYPE_MAP.put("RM", "2E524D46"); // Real Media (rm) FILE_TYPE_MAP.put("RM", "2E524D46"); // Real Media (rm)
FILE_TYPE_MAP.put("MPG", "000001BA"); // FILE_TYPE_MAP.put("MPG", "000001BA"); //
FILE_TYPE_MAP.put("MOV", "6D6F6F76"); // Quicktime (mov) FILE_TYPE_MAP.put("MOV", "6D6F6F76"); // Quicktime (mov)
FILE_TYPE_MAP.put("ASF", "3026B2758E66CF11"); // Windows Media (asf) FILE_TYPE_MAP.put("ASF", "3026B2758E66CF11"); // Windows Media (asf)
FILE_TYPE_MAP.put("MID", "4D546864"); // MIDI (mid) FILE_TYPE_MAP.put("MID", "4D546864"); // MIDI (mid)
} }
public final static String contentType(File file) { public final static String contentType(File file) {
try { try {
return Files.probeContentType(file.toPath()); return Files.probeContentType(file.toPath());
} catch (IOException e) { } catch (IOException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} }
} }
public final static String contentType(String fullName) { public final static String contentType(String fullName) {
try { try {
return Files.probeContentType(Paths.get(fullName)); return Files.probeContentType(Paths.get(fullName));
} catch (IOException e) { } catch (IOException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} }
} }
public final static String getExtName(File file) { public final static String getExtName(File file) {
String extName = null; String extName = null;
String fileName = file.getName(); String fileName = file.getName();
if(fileName.contains(".")) { if(fileName.contains(".")) {
extName = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); extName = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
} }
return extName; return extName;
} }
public final static String imageType(File imageFile) { public final static String imageType(File imageFile) {
if (isImage(imageFile)) { if (isImage(imageFile)) {
ImageInputStream iis = null; ImageInputStream iis = null;
try { try {
iis = ImageIO.createImageInputStream(imageFile); iis = ImageIO.createImageInputStream(imageFile);
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis); Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) { if (!iter.hasNext()) {
return null; return null;
} }
ImageReader reader = iter.next(); ImageReader reader = iter.next();
iis.close(); iis.close();
return reader.getFormatName(); return reader.getFormatName();
} catch (IOException e) { } catch (IOException e) {
return getExtName(imageFile); return getExtName(imageFile);
} finally { } finally {
try { try {
iis.close(); iis.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} else { } else {
return null; return null;
} }
} }
public final static String fileType(File file) { public final static String fileType(File file) {
byte[] b = new byte[50]; byte[] b = new byte[50];
InputStream is = null; InputStream is = null;
try { try {
String extName = getExtName(file); String extName = getExtName(file);
if(StringUtil.isNotBlank(extName)) { if(StringUtil.isNotBlank(extName)) {
return extName; return extName;
} else { } else {
is = new FileInputStream(file); is = new FileInputStream(file);
is.read(b); is.read(b);
return fileType(b); return fileType(b);
} }
} catch (IOException e) { } catch (IOException e) {
return getExtName(file); return getExtName(file);
} finally { } finally {
try { try {
if(is != null) { if(is != null) {
is.close(); is.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public final static String fileType(byte[] b) { public final static String fileType(byte[] b) {
String filetypeHex = String.valueOf(fileHex(b)); String filetypeHex = String.valueOf(fileHex(b));
Iterator<Entry<String, String>> entryiterator = FILE_TYPE_MAP.entrySet().iterator(); Iterator<Entry<String, String>> entryiterator = FILE_TYPE_MAP.entrySet().iterator();
while (entryiterator.hasNext()) { while (entryiterator.hasNext()) {
Entry<String, String> entry = entryiterator.next(); Entry<String, String> entry = entryiterator.next();
String fileTypeHexValue = entry.getValue(); String fileTypeHexValue = entry.getValue();
if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) { if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
return entry.getKey(); return entry.getKey();
} }
} }
return null; return null;
} }
public static final boolean isImage(File file) { public static final boolean isImage(File file) {
boolean flag = false; boolean flag = false;
try { try {
BufferedImage bufreader = ImageIO.read(file); BufferedImage bufreader = ImageIO.read(file);
int width = bufreader.getWidth(); int width = bufreader.getWidth();
int height = bufreader.getHeight(); int height = bufreader.getHeight();
if (width == 0 || height == 0) { if (width == 0 || height == 0) {
flag = false; flag = false;
} else { } else {
flag = true; flag = true;
} }
} catch (IOException e) { } catch (IOException e) {
flag = false; flag = false;
} catch (Exception e) { } catch (Exception e) {
flag = false; flag = false;
} }
return flag; return flag;
} }
public final static String fileHex(byte[] b) { public final static String fileHex(byte[] b) {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
if (b == null || b.length <= 0) { if (b == null || b.length <= 0) {
return null; return null;
} }
for (int i = 0; i < b.length; i++) { for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xFF; int v = b[i] & 0xFF;
String hv = Integer.toHexString(v); String hv = Integer.toHexString(v);
if (hv.length() < 2) { if (hv.length() < 2) {
stringBuilder.append(0); stringBuilder.append(0);
} }
stringBuilder.append(hv); stringBuilder.append(hv);
} }
return stringBuilder.toString(); return stringBuilder.toString();
} }
/** /**
* 将字节数组转化为文件 * 将字节数组转化为文件
* @param bytes * @param bytes
* @param filename * @param filename
* @return * @return
*/ */
public static File bytesToFile(byte[] bytes, File file) { public static File bytesToFile(byte[] bytes, File file) {
File parent = file.getParentFile(); File parent = file.getParentFile();
if(!parent.exists()) { if(!parent.exists()) {
parent.mkdirs(); parent.mkdirs();
} }
BufferedOutputStream stream = null; BufferedOutputStream stream = null;
try { try {
FileOutputStream fstream = new FileOutputStream(file); FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream); stream = new BufferedOutputStream(fstream);
stream.write(bytes); stream.write(bytes);
} catch (Exception e) { } catch (Exception e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} finally { } finally {
if (stream != null) { if (stream != null) {
try { try {
stream.close(); stream.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
return file; return file;
} }
public static File bytesToFile(byte[] bytes, String filename) { public static File bytesToFile(byte[] bytes, String filename) {
return bytesToFile(bytes, new File(filename)); return bytesToFile(bytes, new File(filename));
} }
/** /**
* 将字节数组转化为文件 * 将字节数组转化为文件
* @param bytes * @param bytes
* @param filenames * @param filenames
* @return * @return
*/ */
public static File[] bytesToFiles(byte[][] bytes, String[] filenames) { public static File[] bytesToFiles(byte[][] bytes, String[] filenames) {
File[] files = new File[filenames.length]; File[] files = new File[filenames.length];
for(int i = 0; i < filenames.length; i++) { for(int i = 0; i < filenames.length; i++) {
files[i] = bytesToFile(bytes[i], filenames[i]); files[i] = bytesToFile(bytes[i], filenames[i]);
} }
return files; return files;
} }
/** /**
* 将文件转化为字节数组 * 将文件转化为字节数组
* @param file * @param file
* @return * @return
*/ */
public static byte[] fileToBytes(File file) { public static byte[] fileToBytes(File file) {
byte[] bytes = null; byte[] bytes = null;
try { try {
FileInputStream fis = new FileInputStream(file); FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream(102400); ByteArrayOutputStream baos = new ByteArrayOutputStream(102400);
byte[] b = new byte[102400]; byte[] b = new byte[102400];
int n; int n;
while ((n = fis.read(b)) != -1) { while ((n = fis.read(b)) != -1) {
baos.write(b, 0, n); baos.write(b, 0, n);
} }
fis.close(); fis.close();
baos.close(); baos.close();
bytes = baos.toByteArray(); bytes = baos.toByteArray();
} catch (Exception e) { } catch (Exception e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} }
return bytes; return bytes;
} }
/** /**
* 将文件转化为字节数组 * 将文件转化为字节数组
* @param files * @param files
* @return * @return
*/ */
public static byte[][] filesToBytes(File[] files) { public static byte[][] filesToBytes(File[] files) {
byte[][] datas = new byte[files.length][]; byte[][] datas = new byte[files.length][];
for(int i = 0; i < files.length; i++) { for(int i = 0; i < files.length; i++) {
datas[i] = fileToBytes(files[i]); datas[i] = fileToBytes(files[i]);
} }
return datas; return datas;
} }
/** /**
* 复制文件或文件夹 * 复制文件或文件夹
* *
* @param src 源文件 * @param src 源文件
* @param des 目标文件 * @param des 目标文件
* @throws IOException 异常时抛出 * @throws IOException 异常时抛出
*/ */
public static void fileCopy(File src, File des) { public static void fileCopy(File src, File des) {
if (!src.exists()) { if (!src.exists()) {
return; return;
} }
if (src.isFile()) { if (src.isFile()) {
InputStream ins = null; InputStream ins = null;
FileOutputStream outs = null; FileOutputStream outs = null;
try { try {
ins = new FileInputStream(src); ins = new FileInputStream(src);
outs = new FileOutputStream(des); outs = new FileOutputStream(des);
byte[] buffer = new byte[1024 * 512]; byte[] buffer = new byte[1024 * 512];
int length; int length;
while ((length = ins.read(buffer)) != -1) { while ((length = ins.read(buffer)) != -1) {
outs.write(buffer, 0, length); outs.write(buffer, 0, length);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
ins.close(); ins.close();
outs.flush(); outs.flush();
outs.close(); outs.close();
} catch (IOException e) { } catch (IOException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} }
} }
} else { } else {
des.mkdirs(); des.mkdirs();
for (File sf : src.listFiles()) { for (File sf : src.listFiles()) {
fileCopy(sf, new File(des.getAbsolutePath() + File.separator + sf.getName())); fileCopy(sf, new File(des.getAbsolutePath() + File.separator + sf.getName()));
} }
} }
} }
/** /**
* 移动文件 * 移动文件
* @param src 原文件 * @param src 原文件
* @param des 目标文件 * @param des 目标文件
* @throws IOException * @throws IOException
*/ */
public static void fileMove(File src, File des) { public static void fileMove(File src, File des) {
if(src != null) { if(src != null) {
File parent = des.getParentFile(); File parent = des.getParentFile();
if(!parent.exists()) { if(!parent.exists()) {
parent.mkdirs(); parent.mkdirs();
} }
if(!src.renameTo(des)) { if(!src.renameTo(des)) {
fileCopy(src, des); fileCopy(src, des);
fileDelete(src); fileDelete(src);
} }
} else { } else {
throw new FileUtilException("要移动的源文件不存在:" + src); throw new FileUtilException("要移动的源文件不存在:" + src);
} }
} }
/** /**
* 删除文件 * 删除文件
* @param file 目标文件 * @param file 目标文件
*/ */
public static void fileDelete(File... files) { public static void fileDelete(File... files) {
for(File file : files) { for(File file : files) {
if (file.exists()) { if (file.exists()) {
if (file.isFile()) { if (file.isFile()) {
file.delete(); file.delete();
} else { } else {
for (File f : file.listFiles()) { for (File f : file.listFiles()) {
fileDelete(f); fileDelete(f);
} }
file.delete(); file.delete();
} }
} }
} }
} }
public static byte[] streamToBytes(InputStream instream) { public static byte[] streamToBytes(InputStream instream) {
byte[] bytes = null; byte[] bytes = null;
try { try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(102400); ByteArrayOutputStream baos = new ByteArrayOutputStream(102400);
byte[] b = new byte[102400]; byte[] b = new byte[102400];
int n; int n;
while ((n = instream.read(b)) != -1) { while ((n = instream.read(b)) != -1) {
baos.write(b, 0, n); baos.write(b, 0, n);
} }
instream.close(); instream.close();
baos.close(); baos.close();
bytes = baos.toByteArray(); bytes = baos.toByteArray();
} catch (Exception e) { } catch (Exception e) {
throw new FileUtilException("将输入流转换为字节数组异常", e); throw new FileUtilException("将输入流转换为字节数组异常", e);
} }
return bytes; return bytes;
} }
public static File streamToFile(InputStream instream, File file) { public static File streamToFile(InputStream instream, File file) {
FileUtil.createFile(file); FileUtil.createFile(file);
byte[] bytes = FileUtil.streamToBytes(instream); byte[] bytes = FileUtil.streamToBytes(instream);
return FileUtil.bytesToFile(bytes, file); return FileUtil.bytesToFile(bytes, file);
} }
public static File streamToFile(InputStream instream, String fileName) { public static File streamToFile(InputStream instream, String fileName) {
return FileUtil.streamToFile(instream, new File(fileName)); return FileUtil.streamToFile(instream, new File(fileName));
} }
public static void stringToFile(File file, String... strings) { public static void stringToFile(File file, String... strings) {
FileOutputStream fos = null; FileOutputStream fos = null;
OutputStreamWriter osw = null; OutputStreamWriter osw = null;
Writer writer = null; Writer writer = null;
try { try {
if(!file.getParentFile().exists()) { if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
fos = new FileOutputStream(file); fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos, "UTF-8"); osw = new OutputStreamWriter(fos, "UTF-8");
writer = new BufferedWriter(osw); writer = new BufferedWriter(osw);
for(String string : strings) { for(String string : strings) {
writer.append(string).append(System.getProperty("line.separator")); writer.append(string).append(System.getProperty("line.separator"));
} }
} catch (IOException e) { } catch (IOException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} finally { } finally {
try { try {
writer.close(); writer.close();
osw.close(); osw.close();
fos.close(); fos.close();
} catch (IOException e) { } catch (IOException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} }
} }
} }
public static void stringToFile(String fileFullName, String... strings) { public static void stringToFile(String fileFullName, String... strings) {
FileUtil.stringToFile(new File(fileFullName), strings); FileUtil.stringToFile(new File(fileFullName), strings);
} }
public static String fileToString(File file, String charset) { public static String fileToString(File file, String charset) {
try { try {
return new String(FileUtil.fileToBytes(file), charset); return new String(FileUtil.fileToBytes(file), charset);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new FileUtilException("Unsupported charset:" + charset, e); throw new FileUtilException("Unsupported charset:" + charset, e);
} }
} }
public static String fileToString(String fileFullName, String charset) { public static String fileToString(String fileFullName, String charset) {
return FileUtil.fileToString(new File(fileFullName), charset); return FileUtil.fileToString(new File(fileFullName), charset);
} }
public static String fileToString(File file) { public static String fileToString(File file) {
return FileUtil.fileToString(file, "UTF-8"); return FileUtil.fileToString(file, "UTF-8");
} }
public static String fileToString(String fileFullName) { public static String fileToString(String fileFullName) {
return FileUtil.fileToString(new File(fileFullName)); return FileUtil.fileToString(new File(fileFullName));
} }
public static File fileFromClasspath(String name) { public static File fileFromClasspath(String name) {
String fullName = FileUtil.class.getResource(name).getPath(); String fullName = FileUtil.class.getResource(name).getPath();
return new File(fullName); return new File(fullName);
} }
public static File createFile(String name) { public static File createFile(String name) {
return FileUtil.createFile(new File(name)); return FileUtil.createFile(new File(name));
} }
public static File createFile(File file) { public static File createFile(File file) {
File folder = file.getParentFile(); File folder = file.getParentFile();
if(!(folder.exists() && folder.isDirectory())) { if(!(folder.exists() && folder.isDirectory())) {
folder.mkdirs(); folder.mkdirs();
} }
if(!file.exists() || file.isDirectory()) { if(!file.exists() || file.isDirectory()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} }
} else { } else {
throw new FileUtilException("文件已经存在: " + file.getAbsolutePath()); throw new FileUtilException("文件已经存在: " + file.getAbsolutePath());
} }
return file; return file;
} }
public static File createFolder(String name) { public static File createFolder(String name) {
File folder = new File(name); File folder = new File(name);
if(!folder.exists() || folder.isFile()) { if(!folder.exists() || folder.isFile()) {
folder.mkdirs(); folder.mkdirs();
} }
return folder; return folder;
} }
public static void objectToFile(Object obj, File file) { public static void objectToFile(Object obj, File file) {
FileOutputStream fos = null; FileOutputStream fos = null;
ObjectOutputStream oos = null; ObjectOutputStream oos = null;
try { try {
fos = new FileOutputStream(file); fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos); oos = new ObjectOutputStream(fos);
oos.writeObject(obj); oos.writeObject(obj);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} catch (IOException e) { } catch (IOException e) {
throw new FileUtilException(e); throw new FileUtilException(e);
} finally { } finally {
try { try {
oos.close(); oos.close();
fos.close(); fos.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static InputStream bytesToInputStream(byte[] bytes) { public static InputStream bytesToInputStream(byte[] bytes) {
return new ByteArrayInputStream(bytes); return new ByteArrayInputStream(bytes);
} }
/** /**
* 序列化 * 序列化
* *
* @param object * @param object
* @return * @return
* @throws IOException * @throws IOException
*/ */
public static byte[] objToBytes(Object object) throws IOException { public static byte[] objToBytes(Object object) throws IOException {
ObjectOutputStream oos = null; ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null; ByteArrayOutputStream baos = null;
try { try {
baos = new ByteArrayOutputStream(); baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos); oos = new ObjectOutputStream(baos);
oos.writeObject(object); oos.writeObject(object);
byte[] bytes = baos.toByteArray(); byte[] bytes = baos.toByteArray();
return bytes; return bytes;
} finally { } finally {
oos.flush(); oos.flush();
oos.close(); oos.close();
baos.flush(); baos.flush();
baos.close(); baos.close();
} }
} }
/** /**
* 反序列化 * 反序列化
* *
* @param bytes * @param bytes
* @return * @return
* @throws IOException * @throws IOException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
public static Object bytesToObj(byte[] bytes) throws IOException, ClassNotFoundException { public static Object bytesToObj(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = null; ByteArrayInputStream bais = null;
ObjectInputStream ois = null; ObjectInputStream ois = null;
try { try {
bais = new ByteArrayInputStream(bytes); bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais); ois = new ObjectInputStream(bais);
return ois.readObject(); return ois.readObject();
} finally { } finally {
ois.close(); ois.close();
bais.close(); bais.close();
} }
} }
public static boolean isNotExists(String jspname) { public static boolean isNotExists(String jspname) {
return !new File(jspname).exists(); return !new File(jspname).exists();
} }
/** /**
* *
* @Title: inputStreamToFile * @Title: inputStreamToFile
* @Description: TODO(这里用一句话描述这个方法的作用) * @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param ins * @param: @param ins
* @param: @param file * @param: @param file
* @return: void * @return: void
* @throws * @throws
*/ */
public static void inputStreamToFile(InputStream ins,File file) { public static void inputStreamToFile(InputStream ins,File file) {
try { try {
OutputStream os = new FileOutputStream(file); OutputStream os = new FileOutputStream(file);
int bytesRead = 0; int bytesRead = 0;
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead); os.write(buffer, 0, bytesRead);
} }
os.close(); os.close();
ins.close(); ins.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static Object fileToObject(File file) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
return ois.readObject();
} catch (FileNotFoundException e) {
throw new FileUtilException(e);
} catch (IOException e) {
throw new FileUtilException(e);
} catch (ClassNotFoundException e) {
throw new FileUtilException(e);
} finally {
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment