com.lone.common.util.FileUtils Maven / Gradle / Ivy
The newest version!
package com.lone.common.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
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.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.FieldPosition;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import lombok.extern.slf4j.Slf4j;
/**
* 文件操作工具类
*
*/
@Slf4j
public class FileUtils {
/** This Format for format the data to special format. */
private final static Format dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
/** The FieldPosition. */
private static final FieldPosition HELPER_POSITION = new FieldPosition(0);
/**
* 删除文件
*
* @param filename
* String 文件路径
* @throws IOException
*/
public static void delFile(String filePath) throws IOException {
File file = new File(filePath);
if (filePath == null || filePath.equals("")) {
} else {
if (file.exists()) {
file.delete();
}
}
}
/**
* 读取源文件内容
*
* @param filename
* String 文件路径
* @throws IOException
* @return byte[] 文件内容
*/
public static byte[] readFile(String filename) throws IOException {
File file = new File(filename);
if (filename == null || filename.equals("")) {
throw new NullPointerException("无效的文件路径");
}
long len = file.length();
byte[] bytes = new byte[(int) len];
BufferedInputStream bufferedInputStream = new BufferedInputStream(
new FileInputStream(file));
int r = bufferedInputStream.read(bytes);
if (r != len)
throw new IOException("读取文件不正确");
bufferedInputStream.close();
return bytes;
}
/**
* 将数据写入文件
*
* @param data
* byte[]
* @throws IOException
*/
public static File writeToFile(byte[] data, String filename)
throws IOException {
File file = new File(filename);
file.getParentFile().mkdirs();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(file));
bufferedOutputStream.write(data);
bufferedOutputStream.close();
return file;
}
/**
* 从jar文件里读取class
*
* @param filename
* String
* @throws IOException
* @return byte[]
*/
public byte[] readFileJar(String filename) throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(
getClass().getResource(filename).openStream());
int len = bufferedInputStream.available();
byte[] bytes = new byte[len];
int r = bufferedInputStream.read(bytes);
if (len != r) {
bytes = null;
throw new IOException("读取文件不正确");
}
bufferedInputStream.close();
return bytes;
}
/**
* 读取网络流,为了防止中文的问题,在读取过程中没有进行编码转换,而且采取了动态的byte[]的方式获得所有的byte返回
*
* @param bufferedInputStream
* BufferedInputStream
* @throws IOException
* @return byte[]
*/
public byte[] readUrlStream(BufferedInputStream bufferedInputStream)
throws IOException {
byte[] bytes = new byte[100];
byte[] bytecount = null;
int n = 0;
int ilength = 0;
while ((n = bufferedInputStream.read(bytes)) >= 0) {
if (bytecount != null)
ilength = bytecount.length;
byte[] tempbyte = new byte[ilength + n];
if (bytecount != null) {
System.arraycopy(bytecount, 0, tempbyte, 0, ilength);
}
System.arraycopy(bytes, 0, tempbyte, ilength, n);
bytecount = tempbyte;
if (n < bytes.length)
break;
}
return bytecount;
}
/**
* 读取网络流,为了防止中文的问题,在读取过程中没有进行编码转换,而且采取了动态的byte[]的方式获得所有的byte返回
*
* @param bufferedInputStream
* BufferedInputStream
* @throws IOException
* @return byte[]
*/
public static byte[] streamToByte(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b, 0, b.length)) != -1) {
baos.write(b, 0, len);
}
byte[] buffer = baos.toByteArray();
return buffer;
}
/**
* InputStream --> String
*
* @param is
* @return
* @throws IOException
*/
public static String inputStream2String(InputStream is) throws IOException {
String content = null;
UnicodeReader ur = new UnicodeReader(is, "UTF-8");
BufferedReader in = new BufferedReader(ur);
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
content = buffer.toString();
return content;
}
/**
* InputStream --> File
*
* @param ins
* @param file
* @throws IOException
*/
public static void inputstreamtofile(InputStream ins, File file)
throws IOException {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = ins.read(buffer, 0, buffer.length)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
}
/**
* XML org.w3c.dom.Document 转 String
*/
public static String docToString(Document doc) throws Exception{
// XML转字符串
String rtnStr = null;
try {
DOMSource domSource = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
// tf.setAttribute("indent-number", new Integer(2));
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(domSource, new StreamResult(stringWriter));
rtnStr = stringWriter.getBuffer().toString();
return rtnStr;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* String 转 XML org.w3c.dom.Document
*/
public static Document stringToDoc(String xmlStr) throws Exception{
// 字符串转XML
Document doc = null;
try {
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
doc = builder.parse(is);
return doc;
} catch (ParserConfigurationException e) {
e.printStackTrace();
throw e;
} catch (SAXException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* 取得后缀名
*
* @param astrFileNm
* 文件名称
* @return 后缀名
*/
public static String getExtension(String astrFileNm) {
String strRet = "";
if (astrFileNm != null) {
int iIndex = astrFileNm.lastIndexOf('.', astrFileNm.length());
if (iIndex != -1) {
strRet = astrFileNm.substring(++iIndex);
}
}
return strRet;
}
/**
* 取得文件名(不包含后缀名)
*
* @param astrFileNm
* 文件名称
* @return 后缀名
*/
public static String getFileName(String astrFileNm) {
String strRet = "";
if (astrFileNm != null) {
int startIndex = astrFileNm.lastIndexOf('/', astrFileNm.length());
int endIndex = astrFileNm.lastIndexOf('.', astrFileNm.length());
if (startIndex != -1) {
strRet = astrFileNm.substring(++startIndex, endIndex);
}
}
return strRet;
}
/**
* 取得文件名(包含后缀名)
*
* @param astrFileNm
* 文件名称
* @return 后缀名
*/
public static String getFileNameNoPath(String astrFileNm) {
String strRet = "";
if (astrFileNm != null) {
int startIndex = astrFileNm.lastIndexOf('/', astrFileNm.length());
if (startIndex != -1) {
strRet = astrFileNm.substring(++startIndex);
}
}
return strRet;
}
/**
* 时间格式生成序列
*
* @return String
*/
public static synchronized String generateSequenceNo() {
Calendar rightNow = Calendar.getInstance();
StringBuffer sb = new StringBuffer();
dateFormat.format(rightNow.getTime(), sb, HELPER_POSITION);
return sb.toString();
}
/**
* 获取文件扩展名
*
* @param filename
* @return
*/
public static String getExtend(String filename) {
return getExtend(filename, "");
}
/**
* 获取文件扩展名
*
* @param filename
* @return
*/
public static String getExtend(String filename, String defExt) {
if ((filename != null) && (filename.length() > 0)) {
int i = filename.lastIndexOf('.');
if ((i > 0) && (i < (filename.length() - 1))) {
return (filename.substring(i+1)).toLowerCase();
}
}
return defExt.toLowerCase();
}
/**
* 获取文件名称[不含后缀名]
*
* @param
* @return String
*/
public static String getFilePrefix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(0, splitIndex).replaceAll("\\s*", "");
}
/**
* 获取文件名称[不含后缀名]
* 不去掉文件目录的空格
* @param
* @return String
*/
public static String getFilePrefix2(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(0, splitIndex);
}
/**
* 获取文件名称[含后缀名]
* 不去掉文件目录的空格
* @param
* @return String
*/
public static String getFileAfterfix3(String fileName, String str) {
int splitIndex = fileName.lastIndexOf(str);
return fileName.substring(splitIndex, fileName.length());
}
/**
* 文件复制
*方法摘要:这里一句话描述方法的用途
*@param
*@return void
*/
public static void copyFile(String inputFile,String outputFile) throws FileNotFoundException{
File sFile = new File(inputFile);
File tFile = new File(outputFile);
if (!tFile.exists()) {
tFile.mkdirs();
}
FileInputStream fis = new FileInputStream(sFile);
FileOutputStream fos = new FileOutputStream(tFile);
int temp = 0;
byte[] buf = new byte[10240];
try {
while((temp = fis.read(buf))!=-1){
fos.write(buf, 0, temp);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断文件是否为图片
*
*
* @param filename
* 文件名
* 判断具体文件类型
* @return 检查后的结果
* @throws Exception
*/
public static boolean isPicture(String filename) {
// 文件名称为空的场合
if (MyConvertUtils.isEmpty(filename)) {
// 返回不和合法
return false;
}
// 获得文件后缀名
//String tmpName = getExtend(filename);
String tmpName = filename;
// 声明图片后缀名数组
String imgeArray[][] = { { "bmp", "0" }, { "dib", "1" },
{ "gif", "2" }, { "jfif", "3" }, { "jpe", "4" },
{ "jpeg", "5" }, { "jpg", "6" }, { "png", "7" },
{ "tif", "8" }, { "tiff", "9" }, { "ico", "10" } };
// 遍历名称数组
for (int i = 0; i < imgeArray.length; i++) {
// 判断单个类型文件的场合
if (imgeArray[i][0].equals(tmpName.toLowerCase())) {
return true;
}
}
return false;
}
/**
* 判断文件是否为DWG
*
*
* @param filename
* 文件名
* 判断具体文件类型
* @return 检查后的结果
* @throws Exception
*/
public static boolean isDwg(String filename) {
// 文件名称为空的场合
if (MyConvertUtils.isEmpty(filename)) {
// 返回不和合法
return false;
}
// 获得文件后缀名
String tmpName = getExtend(filename);
// 声明图片后缀名数组
if (tmpName.equals("dwg")) {
return true;
}
return false;
}
/**
* 删除指定的文件
*
* @param strFileName
* 指定绝对路径的文件名
* @return 如果删除成功true否则false
*/
public static boolean delete(String strFileName) {
File fileDelete = new File(strFileName);
if (!fileDelete.exists() || !fileDelete.isFile()) {
log.info("错误: " + strFileName + "不存在!");
return false;
}
log.info("--------成功删除文件---------"+strFileName);
return fileDelete.delete();
}
/**
* 清空文件内容
*
* @param path
*/
public static void clearFile(String path) {
try {
FileOutputStream fos = new FileOutputStream(new File(path));
fos.write("".getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}