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

加个方法

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