文件的各種操作工具類

package zj.io.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import zj.check.util.CheckUtil;
import zj.common.KV;
import zj.common.VVV;
import zj.common.exception.ServiceException;
import zj.date.util.DateUtil;
import zj.io.model.ICopyFilesCallBack;
import zj.io.model.IJarCallBackRead;
import zj.io.model.IJarCallBackWrite;
import zj.io.model.JarCallBackRead;
import zj.io.model.JarClass;
import zj.io.model.JarParams;
import zj.io.service.FileFilterI;
import zj.io.service.IReadFilesCall;
import zj.io.service.ReadLinesBatchCallI;
import zj.io.service.ReadLinesCallI;
/**
* 類名 :FileUtil<br>
* 概況 :文件工具類<br>
* OutputStreamWriter/Reader->charsetName 一般情況下是:先打開的后關閉,后打開的先關閉
*
* @version 1.00 (2011.12.02)
* @author SHNKCS 張軍 {@link <a target=_blank href=http://www.dlhighland.cn>張軍個人網站</a> <a target=_blank href=http://user.qzone.qq.com/360901061/>張軍QQ空間</a>}
*/
public class FileUtil implements Serializable {
private static final long serialVersionUID = 1L;
/** 寫文件換行標識 **/
// System.getProperty("line.separator").equals(FileUtil.LINE_SEPARATOR)->true
public static String LINE_SEPARATOR;// = System.getProperty("line.separator");
/** 文件分割符:/,\\ **/
public static final String SEPARATOR = File.separator;
private transient static final Logger logger = Logger.getLogger(FileUtil.class);
public static final int BUFSIZE = 8192;
static {
// avoid security issues
StringBuilderWriter buf = new StringBuilderWriter(4);
PrintWriter out = new PrintWriter(buf);
out.println();
LINE_SEPARATOR = buf.toString();
out.close();
}
/**
* 追加文件內容
*
* @param file
* 文件
* @param content
* 內容
*/
public final static void appendContentByFileWriter(File file, String content) {
FileWriter fw = null;
PrintWriter pw = null;
try {
fileMkdir(file);
// 如果文件存在,則追加內容;如果文件不存在,則創建文件
fw = new FileWriter(file, true);
pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
fw.flush();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
pw.close();
fw.close();
} catch (Exception e) {
}
}
}
/**
* 追加文件內容
*
* @param file
* 文件
* @param content
* 內容
*/
public final static void appendContentByBufferedWriter(File file, String content) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
out.write(content + FileUtil.LINE_SEPARATOR);
out.flush();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
/**
* 追加文件內容
*
* @param file
* 文件
* @param content
* 內容
*/
public final static void appendContentByRandomAccessFile(File file, String content) {
RandomAccessFile raf = null;
try {
// 打開一個隨機訪問文件流,按讀寫方式
raf = new RandomAccessFile(file.getAbsolutePath(), "rw");
// 文件長度,字節數
long fileLength = raf.length();
// 將寫文件指針移到文件尾。
raf.seek(fileLength);
// raf.skipBytes(skipLength);
raf.write((content + FileUtil.LINE_SEPARATOR).getBytes());
raf.close();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
raf.close();
} catch (Exception e) {
}
}
}
/**
* 追加文件內容
*
* @param file
* 文件
* @param content
* 內容
* @param before
* 在前面
*/
@Deprecated
public final static void appendContentByRandomAccessFile(File file, String content, boolean before) {
appendContentByRandomAccessFile(file, content, before ? 0 : Long.MAX_VALUE);
}
/**
* 追加文件內容
*
* @param file
* 文件
* @param content
* 內容
* @param skipLength
* 在第幾行寫
*/
@Deprecated
public final static void appendContentByRandomAccessFile(File file, String content, long skipLength) {
RandomAccessFile raf = null;
try {
// 打開一個隨機訪問文件流,按讀寫方式
raf = new RandomAccessFile(file.getAbsolutePath(), "rw");
// 文件長度,字節數
long fileLength = raf.length();
if (skipLength < 0) {
skipLength = 0;
} else if (skipLength == Long.MAX_VALUE) {
skipLength = fileLength;
} else {
if (skipLength > fileLength) {
skipLength = fileLength;
}
}
// 將寫文件指針移到文件尾。
raf.seek(skipLength);
// raf.skipBytes(skipLength);
raf.write((content + FileUtil.LINE_SEPARATOR).getBytes());
raf.close();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
raf.close();
} catch (Exception e) {
}
}
}
/**
* 監聽文件夾變化
*
* @param rootDir
* 文件夾路徑
* @param adaptor
* 監聽文件適配器
*/
public static void listenerFile(final String rootDir, final FileAlterationListenerAdaptor adaptor) {
listenerFile(rootDir, adaptor, 1000);
}
/**
* 監聽文件夾變化
*
* @param rootDir
* 文件夾路徑
* @param adaptor
* 監聽文件適配器
* @param interval
* 輪詢間隔 interval 秒
*/
public static void listenerFile(final String rootDir, final FileAlterationListenerAdaptor adaptor, final long interval) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// logger.info("監聽文件目錄【" + rootDir + "】");
// 輪詢間隔 1 秒
// long interval = TimeUnit.SECONDS.toMillis(1);
// 創建一個文件觀察器用于處理文件的格式
FileAlterationObserver observer = new FileAlterationObserver(rootDir);
// 設置文件變化監聽器
observer.addListener(adaptor);
// 創建文件變化監聽器
FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
// 開始監控
monitor.start();
logger.info("監聽文件目錄【" + rootDir + "】開始啟動");
} catch (Exception e) {
logger.error("監聽出錯", e);
}
}
}).start();
}
/**
* 拷貝文件
*
* @param callBack
* 拷貝回調
*
*/
public static void copyFiles(ICopyFilesCallBack callBack) {
String input = callBack.getInputFile();
String output = callBack.getOutputFile();
try {
// 拷貝文件路徑[輸入文件目錄->拷貝文件路徑]
Collection<String> queryClass = callBack.getCopyFile();
File inputFile = new File(input);
if (!inputFile.exists()) {
throw new ServiceException("輸入文件目錄不存在");
}
File outputFile = new File(output);
if (!outputFile.exists()) {
outputFile.mkdirs();
}
// 查詢所有源文件
List<File> files = new ArrayList<File>();
FileUtil.setFilterFiles(files, input);
// classes路徑前綴
String srcPrefix = "";
input = FileUtil.linuxSeparator(input);
if (!input.endsWith("/")) {
input += "/";
}
// 源文件路徑前綴
srcPrefix = input;
// System.out.println("文件個數[" + files.size() + "]");
for (File inFile : files) {
String lf = FileUtil.linuxSeparator(inFile.getAbsolutePath());
// 過慮后綴
// String includeExt = ".class";
// if (CheckUtil.isNotNull(includeExt) && !lf.endsWith(includeExt)) {
// continue;
// }
// 取得類全路徑com/xxx/xxx/xxx.class
String clsPath = lf.substring(srcPrefix.length());
// System.out.println(lf + "###" + clsPath);
if (queryClass.contains(clsPath)) {
// 拷貝源class
File outFile = new File(output, clsPath);
// 判斷目標文件目錄是否存在
File dstFileDir = outFile.getParentFile();
if (!dstFileDir.exists()) {
dstFileDir.mkdirs();
}
FileUtil.copyFile(inFile, outFile);
// 回調
callBack.copyFile(inFile, outFile);
// System.out.println("源文件【" + inFile.getAbsolutePath() + "】拷貝到->【" + outFile.getAbsolutePath() + "】");
}
}
// System.out.println("文件個數[" + files.size() + "]");
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 獲取進程命令執行打印出來的信息
*
* @param command
* 命令
* @return
*/
public static List<String> cmdProcessInfo(String command) {
return cmdProcessInfo(command, "GBK");
}
/**
* 獲取進程命令執行打印出來的信息
*
* @param command
* 命令
* @param charsetName
* 編碼
* @return
*/
public static List<String> cmdProcessInfo(String command, String charsetName) {
List<String> lists = new ArrayList<String>();
BufferedReader in = null;
Process pro = null;
try {
Runtime r = Runtime.getRuntime();
pro = r.exec(command);
in = new BufferedReader(new InputStreamReader(pro.getInputStream(), charsetName));
String line = in.readLine();
line = IOUtils.readFirstLine(line);
while (line != null) {
lists.add(line);
line = in.readLine();
}
} catch (Exception e) {
throw new ServiceException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (pro != null) {
pro.destroy();
}
}
return lists;
}
/**
* 創建文件目錄
*
* @param file
* 文件/目錄
*/
public static void fileMkdir(File... files) {
if (files == null)
return;
for (File file : files) {
String outputDir = "";
if (file.isDirectory()) {
outputDir = file.getAbsolutePath();
} else {
outputDir = file.getParent();
}
File outputDirFile = new File(outputDir);
if (!outputDirFile.exists()) {
outputDirFile.mkdirs();
}
}
}
/**
* 拷貝文件
*
* @param inputFile
* 輸入文件
* @param outputFile
* 輸出文件
*/
public static void copyFile(File inputFile, File outputFile) {
try {
fileMkdir(outputFile);
FileInputStream inputFIS = new FileInputStream(inputFile);
FileOutputStream outputFOS = new FileOutputStream(outputFile);
IOUtils.copyLarge(inputFIS, outputFOS);
IOUtils.closeQuietly(inputFIS);
IOUtils.closeQuietly(outputFOS);
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 讀取jar包里面指定文件的內容
*
* @param jarFilePath
* jar包文件路徑
* @param fileName
* 文件路徑名
* @throws IOException
*/
public static InputStream jarReadInputStream(String jarFilePath, String fileName) {
JarFile jarFile = null;
try {
jarFile = new JarFile(jarFilePath);
JarEntry entry = jarFile.getJarEntry(fileName);
InputStream is = jarFile.getInputStream(entry);
return FileUtil.copyInputStream(is);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
jarFile.close();
} catch (IOException e) {
}
}
}
/**
* 讀取回調jar文件
*
* @param jarFile
* jar包路徑
* @param entryName
* 要寫的文件名
* @param data
* 文件內容
* @throws Exception
*/
public static void jarRead(IJarCallBackRead call) {
String jarFilePath = call.getFilePath();
if (CheckUtil.isNull(jarFilePath)) {
throw new ServiceException("文件路徑zj.io.model.ICallBackWriteJar.getFilePath()不能為空");
}
// jar文件操作
JarFile jarFile = null;
try {
// 1、首先將原Jar包里的所有內容讀取到內存里,用TreeMap保存
jarFile = new JarFile(jarFilePath);
// 讀取jar包內容
Enumeration<JarEntry> es = jarFile.entries();
while (es.hasMoreElements()) {
// 獲取Jar對象
JarEntry je = es.nextElement();
// 文件名稱
String name = je.getName();
// // 文件大小
// long size = je.getSize();
// // 壓縮后的大小
// long compressedSize = je.getCompressedSize();
// 讀取jar包字節
byte[] b = null;
try {
b = FileUtil.readByteByStream(jarFile.getInputStream(je));
} catch (Exception e) {
b = null;
}
// 放入臨時集合中
boolean isContinue = call.read(je, KV.with(name, b));
if (!isContinue) {
// 中斷
break;
}
}
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
jarFile.close();
} catch (IOException e) {
}
}
}
/**
* 讀取jar文件內容到map中
*
* @param filePath
* jar包路徑
* @throws Exception
*/
public static Map<String, byte[]> jarReadToMap(final String filePath) {
// 可以保持排列的順序,所以用TreeMap 而不用HashMap
final Map<String, byte[]> tm = new TreeMap<String, byte[]>();
jarRead(new JarCallBackRead() {
@Override
public String getFilePath() {
return filePath;
}
@Override
public boolean read(JarEntry je, KV<String, byte[]> kv) {
tm.put(kv.getK(), kv.getV());
return true;
}
});
return tm;
}
/**
* 修改Jar包里的文件或者添加文件
*
* @param call
* {@code jarFile jar包路徑,entryName 要寫的文件名,data 文件內容}
* @throws Exception
*/
public static void jarWrite(IJarCallBackWrite call) {
String filePath = call.getFilePath();
// 可以保持排列的順序,所以用TreeMap 而不用HashMap
Map<String, byte[]> tm = jarReadToMap(filePath);
String newFilePath = call.getNewFilePath();
if (CheckUtil.isNull(newFilePath)) {
newFilePath = filePath;
}
String entryName = call.getEntryName();
byte[] data = call.getEntryData();
boolean override = call.getEntryOverride();
// jar文件操作
JarFile jarFile = null;
JarOutputStream jos = null;
FileOutputStream fos = null;
try {
// 1、首先將原Jar包里的所有內容讀取到內存里,用TreeMap保存
jarFile = new JarFile(filePath);
// 寫出jar文件
fos = new FileOutputStream(newFilePath);
// 創建jar輸出流
jos = new JarOutputStream(fos);
Iterator<Map.Entry<String, byte[]>> it = tm.entrySet().iterator();
// 判斷是否添加新的文件
boolean isExistFile = false;
// 2、將TreeMap重新寫到原jar里,如果TreeMap里已經有entryName文件那么覆蓋,否則在最后添加
while (it.hasNext()) {
Map.Entry<String, byte[]> item = it.next();
// 當前文件名
String name = item.getKey();
// 當前文件字節碼
byte[] tempData = item.getValue();
if (name.equals(entryName)) {
// 如果數據存在,不能執行下面添加操作,覆蓋,名稱相同
isExistFile = true;
if (data != null && override) {
// 覆蓋文件
tempData = data;
}
}
// 回調操作
VVV<Boolean, String, byte[]> result = call.updateData(KV.with(name, tempData));
if (result != null) {
if (!result.getV1()) {
// 刪除此文件
continue;
}
// 重新賦值名稱和數據
name = result.getV2();
tempData = result.getV3();
}
// 實例化jar里的對象
JarEntry entry = new JarEntry(name);
// 放入jar文件中
jos.putNextEntry(entry);
// 寫入字節
jos.write(tempData, 0, tempData.length);
}
if (CheckUtil.isNotNull(entryName) && !isExistFile) {
// 如果不存在文件則添加
// 最后添加
JarEntry newEntry = new JarEntry(entryName);
jos.putNextEntry(newEntry);
jos.write(data, 0, data.length);
}
jos.finish();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
fos.close();
} catch (IOException e) {
}
try {
jos.close();
} catch (IOException e) {
}
try {
jarFile.close();
} catch (IOException e) {
}
}
}
/**
* 深度拷貝流
*
* @param is
* 深度拷貝流
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @throws IOException
*/
public static InputStream copyInputStream(InputStream is) {
try {
// 創建一個新的流
return new ByteArrayInputStream(readByteByStream(is));
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 按行輸出流內容
*
* @param is
* 流,此is不關閉
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @throws IOException
*/
public static void printInputStream(InputStream is) {
printInputStream(is, "GBK");
}
/**
* 按行輸出流內容
*
* @param is
* 流,此is不關閉
* @param charsetName
* 字符集
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @throws IOException
*/
public static void printInputStream(InputStream is, String charsetName) {
BufferedReader reader = null;
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, charsetName);
reader = new BufferedReader(isr);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(reader);
}
}
/**
* 讀取流
*
* @param file
* 文件
* @return 字節數組
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @return 字節流
* @throws Exception
*/
public static byte[] readByteByFile(File file) {
try {
return readByteByStream(new FileInputStream(file));
} catch (IOException e) {
throw new ServiceException(e);
}
}
/**
* 讀取流
*
* @param is
* 輸入流
* @return 字節數組
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @return 字節流
* @throws Exception
*/
public static byte[] readByteByStream(InputStream is) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
byte[] buff = new byte[BUFSIZE];
int len = -1;
while ((len = is.read(buff)) != -1) {
baos.write(buff, 0, len);
}
byte[] b = baos.toByteArray();
return b;
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(baos);
IOUtils.closeQuietly(is);
}
}
/**
* 設置文件目錄/文件的修改時間
*
* @param file
* 文件
* @param lmdate
* 修改的日期
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @return
*/
public static void setLastModified(File file, String lmdate) {
if (file == null || !file.exists()) {
logger.warn("文件不存在,無法設置修改時間");
return;
}
Date ld = DateUtil.parseDate(lmdate);
if (ld == null) {
logger.warn("日期格式不正確");
return;
}
long lastDate = ld.getTime();
if (file.isDirectory()) {
// 讀取文件目錄
List<File> files = new ArrayList<File>();
FileUtil.setFilterFiles(files, file.getAbsolutePath());
for (File $file : files) {
$file.setLastModified(lastDate);
}
} else {
file.setLastModified(lastDate);
}
}
/**
* 移動文件
*
* @param srcFile
* 源文件
* @param destFile
* 目標文件(文件或目錄)
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @return
*/
public static void moveFile(File srcFile, File destFile) throws Exception {
moveFile(srcFile, destFile, false);
}
/**
* 移動文件
*
* @param srcFile
* 源文件
* @param destFile
* 目標文件(文件或目錄)
* @param overrideFile
* 是否覆蓋
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @return
*/
public static void moveFile(File srcFile, File destFile, boolean overrideFile) throws Exception {
// File srcFile = new File("D:/msth/ipo/excel/入圍/復核/復核-20161103.xlsx");
// File destFile = new File("D:/msth/ipo/excel/入圍/復核/backup");
// boolean overrideFile = false;
try {
if (overrideFile) {
// 拷貝文件
if (destFile.isDirectory()) {
try {
FileUtils.copyFileToDirectory(srcFile, destFile);
} catch (Exception e1) {
// 不做處理
}
} else {
try {
FileUtils.copyFile(srcFile, destFile);
} catch (Exception e1) {
// 不做處理
}
}
// 刪除源文件
srcFile.delete();
} else {
if (destFile.isDirectory()) {
FileUtils.moveFileToDirectory(srcFile, destFile, true);
} else {
FileUtils.moveFile(srcFile, destFile);
}
}
} catch (Exception e) {
if (e instanceof FileExistsException) {
// 文件存在
if (destFile.isDirectory()) {
String destPath = srcFile.getAbsolutePath();
File renameDestFile = new File(destFile, FilenameUtils.getBaseName(destPath) + "-" + DateUtil.dateParse(new Date(), "yyyyMMddHHmmssSSS") + "." + FilenameUtils.getExtension(destPath));
FileUtils.moveFile(srcFile, renameDestFile);
} else {
String destPath = destFile.getAbsolutePath();
File renameDestFile = new File(FilenameUtils.getBaseName(destPath) + "-" + DateUtil.dateParse(new Date(), "yyyyMMddHHmmssSSS") + "." + FilenameUtils.getExtension(destPath));
FileUtils.moveFile(srcFile, renameDestFile);
}
} else {
e.printStackTrace();
throw e;
}
}
}
/**
* 取得文件的創建時間
*
* @param file
* @return
*/
public static final String getCreateTime(File file) {
String createTime = "";
try {
Process p = Runtime.getRuntime().exec("cmd /C dir " + file.getAbsolutePath() + " /tc");
InputStream is = p.getInputStream();
// ant下的zip工具默認壓縮編碼為UTF-8編碼, 而winRAR軟件壓縮是用的windows默認的GBK或者GB2312編碼 所以解壓縮時要制定編碼格式
BufferedReader br = new BufferedReader(new InputStreamReader(is, "gbk"));
String line = null;
int i = 0;
while ((line = br.readLine()) != null) {
if (++i == 6) {
createTime = line.substring(0, 17);
}
}
} catch (Exception e) {
createTime = "";
logger.error(e.getMessage());
}
return createTime;
}
/**
* 根據系統改變路徑分割符號
*
* @param path
* 路徑
* @param isSpeEnd
* 是否添加最后分割符
* <p>
* true:添加
* </p>
* <p>
* false:默認
* </p>
* @see #changePathSeparator(String, zj.io.util.ConstantForEnum.ChangePathLastSeparator)
* @return 改變后的系統路徑
*/
@Deprecated
public static final String changePathSeparator(String path, boolean isSpeEnd) {
if (CheckUtil.isNull(path))
return "";
// logger.debug("改變路徑分割符號前path:" + path);
if (SEPARATOR.equals("/")) {
// 非windows系統
path = path.replaceAll("\\\\", "/");
if (isSpeEnd) {
if (!path.endsWith("/")) {
path = path + "/";
}
}
} else {
// windows系統
path = path.replaceAll("/", "\\\\");
if (isSpeEnd) {
if (!path.endsWith("\\")) {
path = path + "\\";
}
}
}
return path;
}
/**
* 根據系統改變路徑分割符號
*
* @param path
* 路徑
* @param sepEnum
* 常量枚舉{@link zj.io.util.ConstantForEnum.ChangePathLastSeparator}
* @return 改變后的系統路徑
*/
public static final String changePathSeparator(String path, ConstantForEnum.ChangePathLastSeparator sepEnum) {
if (CheckUtil.isNull(path))
return "";
// logger.debug("改變路徑分割符號前path:" + path);
if (SEPARATOR.equals("/")) {
path = linuxSeparator(path, sepEnum);
} else {
path = windowsSeparator(path, sepEnum);
}
return path;
}
/**
* 根據系統改變包路徑分割符號
*
* @param packagePath
* 包路徑
* @return 包路徑
*/
public static final String packageToPath(String packagePath) {
if (CheckUtil.isNull(packagePath))
return "";
// logger.debug("改變路徑分割符號前path:" + path);
if (SEPARATOR.equals("/")) {
packagePath = packagePath.replaceAll("\\.", "/");
} else {
packagePath = packagePath.replaceAll("\\.", "\\\\");
}
return packagePath;
}
/**
* window分割符
*
* @param path
* 路徑
* @return 改變后的系統路徑
*/
public static final String windowsSeparator(String path) {
return windowsSeparator(path, ConstantForEnum.ChangePathLastSeparator.NONE);
}
/**
* window分割符
*
* @param path
* 路徑
* @param sepEnum
* 常量枚舉{@link zj.io.util.ConstantForEnum.ChangePathLastSeparator}
* @return 改變后的系統路徑
*/
public static final String windowsSeparator(String path, ConstantForEnum.ChangePathLastSeparator sepEnum) {
if (CheckUtil.isNull(path))
return "";
// windows系統
path = path.replaceAll("/", "\\\\");
if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_BEFORE == sepEnum) {
if (!path.startsWith("\\")) {
path = "\\" + path;
}
}
if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_AFTER == sepEnum) {
if (!path.endsWith("\\")) {
path = path + "\\";
}
}
if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_BEFORE == sepEnum) {
if (path.startsWith("\\")) {
path = path.substring(1);
}
}
if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_AFTER == sepEnum) {
if (path.endsWith("\\")) {
path = path.substring(0, path.length() - 1);
}
}
return path;
}
/**
* linux分割符
*
* @param path
* 路徑
* @return 改變后的系統路徑
*/
public static final String linuxSeparator(String path) {
return linuxSeparator(path, ConstantForEnum.ChangePathLastSeparator.NONE);
}
/**
* linux分割符
*
* @param path
* 路徑
* @param sepEnum
* 常量枚舉{@link zj.io.util.ConstantForEnum.ChangePathLastSeparator}
* @return 改變后的系統路徑
*/
public static final String linuxSeparator(String path, ConstantForEnum.ChangePathLastSeparator sepEnum) {
if (CheckUtil.isNull(path))
return "";
// 非windows系統
path = path.replaceAll("\\\\", "/");
// switch (sepEnum) {
// case ADD_ALL:
// case ADD_BEFORE:
// break;
// case ADD_AFTER:
// break;
// default:
// break;
// }
if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_BEFORE == sepEnum) {
if (!path.startsWith("/")) {
path = "/" + path;
}
}
if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_AFTER == sepEnum) {
if (!path.endsWith("/")) {
path = path + "/";
}
}
if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_BEFORE == sepEnum) {
if (path.startsWith("/")) {
path = path.substring(1);
}
}
if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_AFTER == sepEnum) {
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
}
return path;
}
/**
* 根據系統改變路徑分割符號
*
* @param path
* @return
*/
public static final String changePathSeparator(String path) {
return changePathSeparator(path, ConstantForEnum.ChangePathLastSeparator.NONE);
}
/**
* 獲得文件擴展名及前面的字符串
*
* @param filePath
* E:\\xmls\\iqc_basic_user.xml [E:\xmls\,iqc_basic_user,.xml,false]
* @return
*/
public static final String[] getFileNameExtension(String filePath) {
String[] rtnStrs = new String[4];
rtnStrs[0] = "";
rtnStrs[1] = "";
rtnStrs[2] = "";
rtnStrs[3] = "";
String dirPath = "";
String fileName = "";
String fileExtension = "";
String tempStr = "";
int index = -1;
filePath = changePathSeparator(filePath);
if (CheckUtil.isNotNull(filePath)) {
index = filePath.lastIndexOf(SEPARATOR);
if (index >= 0) {
dirPath = filePath.substring(0, index + 1);
tempStr = filePath.substring(index + 1);
index = tempStr.lastIndexOf(".");
if (index >= 0) {
fileName = tempStr.substring(0, index);
fileExtension = tempStr.substring(index);
}
} else {
index = filePath.lastIndexOf(".");
if (index >= 0) {
fileName = filePath.substring(0, index);
dirPath = fileName;
fileExtension = filePath.substring(index);
} else {
dirPath = filePath;
fileName = filePath;
}
}
}
rtnStrs[0] = dirPath;
rtnStrs[1] = fileName;
rtnStrs[2] = fileExtension;
String diskPath = "";
try {
diskPath = dirPath.substring(dirPath.indexOf("\\") + 1);
} catch (Exception e) {
diskPath = "";
}
if ("".equals(diskPath)) {
rtnStrs[3] = "true";
} else {
rtnStrs[3] = "false";
}
return rtnStrs;
}
/**
* 獲取圖片流
*
* @param file
* @return
* @throws IOException
*/
public static final ImageReader getImageReader(File file) {
try {
ImageReader reader = null;
String fileExtension = FilenameUtils.getExtension(file.getName());
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(fileExtension);
reader = readers.next();
ImageInputStream iis = ImageIO.createImageInputStream(file);
reader.setInput(iis, true);
return reader;
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 創建文件或目錄
*
* @param file
* 文件對象
* @param isFolder
* 是否是目錄
* @return 創建是否成功
* @throws IOException
*/
public static final boolean createFolderOrFile(File file, boolean isFolder) {
if (file == null)
return false;
if (isFolder) {
if (file.exists()) {
if (file.isFile()) {
logger.warn("創建文件夾失敗:將要創建的文件【" + file.getAbsolutePath() + "】重名");
} else if (file.isDirectory()) {
logger.warn("創建文件夾失敗:將要創建的文件夾【" + file.getAbsolutePath() + "】已經存在");
}
return false;
} else {
file.mkdirs();
logger.debug("創建文件夾【" + file.getAbsolutePath() + "】成功!");
return true;
}
} else {
String path = file.getPath();
String[] tempPaths = getFileNameExtension(path);
File fileDir = new File(tempPaths[0]);
if (fileDir.exists()) {
logger.warn("創建文件夾失敗:將要創建的文件夾【" + fileDir.getAbsolutePath() + "】已經存在");
return false;
} else {
fileDir.mkdirs();
logger.debug("創建文件夾【" + fileDir.getAbsolutePath() + "】成功!");
return true;
}
}
}
/**
* 創建文件或目錄
*
* @param file
* @return
* @throws IOException
*/
public static final boolean createFolderOrFile(String file) {
return createFolderOrFile(file, false);
}
/**
* 創建文件或目錄
*
* @param file
* @param isFolder
* @return
* @throws IOException
*/
public static final boolean createFolderOrFile(String file, boolean isFolder) {
if (CheckUtil.isNull(file)) {
return false;
}
file = changePathSeparator(file);
return createFolderOrFile(new File(file), isFolder);
}
/**
* 創建文件
*
* @param file
* @throws IOException
*/
public static final void forceMkdirFolderOrFile(String file) {
if (CheckUtil.isNull(file)) {
return;
}
file = changePathSeparator(file);
forceMkdirFolderOrFile(new File(file));
}
/**
* 創建文件或目錄
*
* @param file
* 文件對象
* @throws IOException
*/
public static final void forceMkdirFolderOrFile(File file) {
try {
if (file == null)
return;
if (!file.exists()) {
// 創建目錄
if (file.isFile()) {
String path = file.getPath();
String[] tempPaths = getFileNameExtension(path);
File fileDir = new File(tempPaths[0]);
if (fileDir.exists()) {
logger.warn("創建文件夾失敗:將要創建的文件夾【" + fileDir.getAbsolutePath() + "】已經存在");
} else {
fileDir.mkdirs();
logger.debug("創建文件夾【" + fileDir.getAbsolutePath() + "】成功!");
}
} else {
file.mkdirs();
logger.debug("創建文件夾【" + file.getAbsolutePath() + "】成功!");
}
}
if (file.isFile()) {
file.createNewFile();
logger.debug("創建文件【" + file.getAbsolutePath() + "】成功!");
}
} catch (Exception e) {
logger.error(e);
}
}
/**
* 創建目錄
*
* @param file
* @return
* @throws IOException
*/
public static final boolean createFolderOrFile(File file) {
return createFolderOrFile(file, false);
}
/**
* 將一個字符串轉化為輸入流
*
* @param sInputString
* @return
*/
public static final InputStream getStringStream(String sInputString) {
return getStringStream(sInputString, "utf-8");
}
/**
* 將一個字符串轉化為輸入流
*
* @param sInputString
* @param charset
* @return
*/
public static final InputStream getStringStream(String sInputString, String charset) {
if (sInputString != null && !sInputString.trim().equals("")) {
try {
ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes(charset));
return tInputStringStream;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 將一個輸入流轉化為字符串
*
* @see #readString(File)
* @param file
* 文件對象
* @return
*/
@Deprecated
public static final String getStreamString(File file) {
try {
return getStreamString(new BufferedInputStream(new FileInputStream(file)));
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 將一個輸入流轉化為字符串
*
* @see #readString(InputStream, boolean)
* @param is
* 輸入流
* @return 文件內容
*/
public static final String getStreamString(InputStream is) {
InputStreamReader isr = null;
if (is != null) {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader((isr = new InputStreamReader(is)));
String sLine = null;
sLine = br.readLine();
sLine = IOUtils.readFirstLine(sLine);
if (sLine != null) {
sb.append(sLine);
while ((sLine = br.readLine()) != null) {
sb.append(sLine);
}
}
return sb.toString();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
try {
if (br != null)
br.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (isr != null)
isr.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (is != null)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 設置一個目錄的所有文件至集合中
*
* @param fileList
* 過慮后的文件集合
* @param dir
* 目錄
* @param filter
* 自定義文件過慮器
* @param defaultFilter
* 默認過慮器
*/
public static final void setFilterFilesLevel(List<File> fileList, String dir, FileFilterI filter, FileFilter defaultFilter, int level) {
File file = new File(dir);
if (!file.exists()) {
logger.warn("文件:" + file.getAbsolutePath() + "不存在");
return;
}
if (filter == null) {
// 自定義filter為空
if (file.isDirectory()) {
File[] files = null;
if (defaultFilter == null) {
files = file.listFiles();
} else {
files = file.listFiles(defaultFilter);
}
if (files == null) {
logger.debug("文件:" + file.getAbsolutePath() + "不存在");
} else {
for (File info : files) {
if (info.isDirectory()) {
fileList.add(info);
setFilterFilesLevel(fileList, info.getPath(), filter, defaultFilter, 0);
} else {
// 如果是文件
fileList.add(info);
}
}
}
} else {
fileList.add(file);
}
} else {
int tempLevel = level + 1;
if (file.isDirectory()) {
// 如果是目錄
if (filter.interrupt(file, fileList)) {
logger.debug("待判斷文件夾:" + file.getAbsolutePath() + "退出");
return;
}
File[] files = null;
if (defaultFilter == null) {
files = file.listFiles();
} else {
files = file.listFiles(defaultFilter);
}
if (files == null) {
logger.debug("文件:" + file.getAbsolutePath() + "不存在");
} else {
for (File info : files) {
if (level == 0) {
// 如果當前是開始目錄,則設置為1
tempLevel = 1;
}
filter.setLevel(tempLevel);
if (filter.accept(info)) {
// 是否接收文件夾或文件
if (info.isDirectory()) {
if (filter.acceptDir(info)) {
// 是否接收文件夾
if (filter.interrupt(info, fileList)) {
logger.debug("循環中待添加文件夾:" + info.getAbsolutePath() + "中斷");
break;
}
fileList.add(info);
}
if (filter.interrupt(info, fileList)) {
logger.debug("待回調文件夾:" + info.getAbsolutePath() + "中斷");
break;
}
setFilterFilesLevel(fileList, info.getPath(), filter, defaultFilter, tempLevel);
} else {
// 如果是文件
if (filter.acceptFile(info)) {
// 是否接受文件
if (filter.interrupt(info, fileList)) {
logger.debug("循環中待添加文件:" + info.getAbsolutePath() + "中斷");
break;
}
fileList.add(info);
}
}
}
}
}
} else {
// 設置當前文件級別
filter.setLevel(tempLevel);
if (filter.accept(file)) {
if (filter.interrupt(file, fileList)) {
logger.debug("待判斷文件:" + file.getAbsolutePath() + "退出");
return;
}
if (filter.acceptFile(file)) {
if (filter.interrupt(file, fileList)) {
logger.debug("待添加文件:" + file.getAbsolutePath() + "中斷");
return;
}
fileList.add(file);
}
}
}
}
}
/**
* 讀取某個文件夾下的所有文件
*
* @param inpath
* 輸入目錄
* @param call
* 讀取文件回調接口
*/
public static void readFiles(File file, IReadFilesCall call) {
try {
if (call == null) {
// 如果無實現,則退出
return;
}
if (call.isInterrupt()) {
return;
}
if (file.isDirectory()) {
// 文件列表信息
File[] filelist = file.listFiles();
// 循環文件列表
for (File thisFile : filelist) {
if (thisFile.isDirectory()) {
// 如果是目錄
// 每個文件回調
call.callback(file);
// 目錄回調
call.directory(thisFile);
// 遞歸調用
readFiles(thisFile, call);
} else {
// 如果是文件
// 每個文件回調
call.callback(thisFile);
// 文件回調
call.file(thisFile);
}
}
} else {
// 每個文件回調
call.callback(file);
// 文件回調
call.file(file);
}
} catch (Exception e) {
logger.error(e);
}
}
/**
* 設置一個目錄的所有文件至集合中
*
* @param fileList
* 過慮后的文件集合
* @param dir
* 目錄
* @param filter
* 自定義文件過慮器
* @param defaultFilter
* 默認過慮器
*/
public static final void setFilterFiles(List<File> fileList, String dir, FileFilterI filter, FileFilter defaultFilter) {
setFilterFilesLevel(fileList, dir, filter, defaultFilter, 0);
}
/**
* 設置一個目錄的所有文件至集合中
*
* @param fileList
* 過慮后的文件集合
* @param dir
* 目錄
* @param defaultFilter
* 默認過慮器
*/
public static final void setFilterFiles(List<File> fileList, String dir, FileFilter defaultFilter) {
setFilterFiles(fileList, dir, null, defaultFilter);
}
/**
* 設置一個目錄的所有文件至集合中
*
* @param fileList
* 過慮后的文件集合
* @param dir
* 目錄
* @param filter
* 自定義文件過慮器
*/
public static final void setFilterFiles(List<File> fileList, String dir, FileFilterI filter) {
setFilterFiles(fileList, dir, filter, null);
}
/**
* 設置一個目錄的所有文件至集合中
*
* @param fileList
* 過慮后的文件集合
* @param dir
* 目錄
*/
public static final void setFilterFiles(List<File> fileList, String dir) {
setFilterFiles(fileList, dir, null, null);
}
/**
* 設置屬性文件的值
*
* @param path
* @param key
* @param value
* @throws Exception
*/
public static final void setProperty(String path, String key, String value) throws Exception {
FileInputStream fis = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
// 配置文件內容解析
Properties prop = new Properties();
prop.load(bis);
bis.close();
fis.close();
FileOutputStream fos = new FileOutputStream(path);
BufferedOutputStream bos = new BufferedOutputStream(fos);
// Properties prop = getProperties(path);
prop.setProperty(key, value);
prop.store(bos, null);
bos.flush();
fos.flush();
bos.close();
fos.close();
}
/**
* 獲取屬性值
*
* @param path
* @param key
* @return
* @throws Exception
*/
public static final String getProperty(String path, String key) throws Exception {
return getProperties(path).getProperty(key);
}
/**
* 獲取屬性對象
*
* @param path
* @param key
* @return
* @throws Exception
*/
public static final Properties getProperties(String path) throws Exception {
FileInputStream fis = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
// 配置文件內容解析
Properties prop = new Properties();
prop.load(bis);
bis.close();
fis.close();
return prop;
}
/**
* 將對象序列化到磁盤文件中
*
* @param t
* 對象
* @param filePath
* 文件路徑
* @throws Exception
*/
public static final <T> void writeObjectToFile(T t, String filePath) throws Exception {
writeObjectToFile(t, new File(filePath));
}
/**
* 將對象序列化到磁盤文件中
*
* @param t
* @param file
* @throws Exception
*/
public static final <T> void writeObjectToFile(T t, File file) throws Exception {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
ObjectOutputStream oos = null;
try {
String[] fileExts = getFileNameExtension(file.getAbsolutePath());
String newFilePath = "";
if (fileExts.length > 0) {
newFilePath += fileExts[0];
}
File extFileDir = new File(newFilePath);
if (!extFileDir.exists()) {
extFileDir.mkdirs();
}
if (fileExts.length > 1) {
newFilePath += fileExts[1];
}
if (fileExts.length > 2) {
newFilePath += fileExts[2];
}
file = new File(newFilePath);
if (file.exists()) {
file.delete();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
oos = new ObjectOutputStream(bos);
oos.writeObject(t);
oos.flush();
} finally {
try {
if (oos != null) {
oos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 反序列化,將字符串轉化為對象
*
* @param serStr
* @return
* @throws Exception
*/
public static final <T> T readStrToObject(String serStr) throws Exception {
return readStrToObject(serStr, "UTF-8");
}
/**
* 反序列化,將字符串轉化為對象
*
* @param serStr
* @param charsetName
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static final <T> T readStrToObject(String serStr, String charsetName) throws Exception {
if (CheckUtil.isNull(serStr))
return null;
T obj = null;
ObjectInputStream ois = null;
ByteArrayInputStream bais = null;
try {
String redStr = "";
redStr = java.net.URLDecoder.decode(serStr, charsetName);
bais = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
ois = new ObjectInputStream(bais);
obj = (T) ois.readObject();
} finally {
try {
if (ois != null) {
ois.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (bais != null) {
bais.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
// //序列化對象為String字符串,先對序列化后的結果進行BASE64編碼,否則不能直接進行反序列化
// public static final String writeObject(Object o) throws Exception {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// ObjectOutputStream oos = new ObjectOutputStream(bos);
// oos.writeObject(o);
// oos.flush();
// oos.close();
// bos.close();
// //return new BASE64Encoder().encode(bos.toByteArray());
// return new String(bos.toByteArray(), "ISO-8859-1");
// }
//
// //反序列化String字符串為對象
//
// public static final Object readObject(String object) throws Exception{
// //ByteArrayInputStream bis = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(object));
// ByteArrayInputStream bis = new ByteArrayInputStream(object.getBytes("ISO-8859-1"));
// ObjectInputStream ois = new ObjectInputStream(bis);
// Object o = null;
// try {
// o = ois.readObject();
// } catch(EOFException e) {
// System.err.print("read finished");
// }
// bis.close();
// ois.close();
// return o;
// }
/**
* 將對象序列化成字符串
*
* @param t
* @return
* @throws Exception
*/
public static final <T> String writeObjectToStr(T t) throws Exception {
if (t == null)
return null;
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
String serStr = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(t);
oos.flush();
baos.flush();
serStr = baos.toString("ISO-8859-1");
serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
} finally {
oos.close();
baos.close();
}
return serStr == null ? "" : serStr;
}
/**
* 反序列化,將磁盤文件轉化為對象
*
* @param filePath
* 文件路徑
* @return
* @throws Exception
*/
public static final <T> T readFileToObject(String filePath) throws Exception {
if (filePath == null || filePath.trim().equals(""))
return null;
File file = new File(filePath);
return readFileToObject(file);
}
/**
* 反序列化,將磁盤文件轉化為對象
*
* @param file
* 文件對象
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static final <T> T readFileToObject(File file) throws Exception {
FileInputStream fis = null;
BufferedInputStream bis = null;
ObjectInputStream ois = null;
T obj = null;
try {
if (!file.exists())
return null;
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
ois = new ObjectInputStream(bis);
obj = (T) ois.readObject();
} finally {
ois.close();
bis.close();
fis.close();
}
return obj;
}
// readLinesCount
// -----------------------------------------------------------------------
public static final long readLinesCount(File file) {
return readLinesCount(file, null);
}
public static final long readLinesCount(File file, String encoding) {
InputStream in = null;
try {
in = FileUtils.openInputStream(file);
return readLinesCount(in, encoding);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(in);
}
}
public static final long readLinesCount(InputStream input, String encoding) {
try {
if (encoding == null) {
return readLinesCount(input);
} else {
InputStreamReader reader = new InputStreamReader(input, encoding);
return readLinesCount(reader);
}
} catch (Exception e) {
throw new ServiceException(e);
}
}
public static final long readLinesCount(InputStream input) {
InputStreamReader reader = new InputStreamReader(input);
return readLinesCount(reader);
}
public static final long readLinesCount(Reader input) {
try {
long lineNum = 0;
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
line = IOUtils.readFirstLine(line);
while (line != null) {
lineNum++;
line = reader.readLine();
}
return lineNum;
} catch (Exception e) {
throw new ServiceException(e);
}
}
// readString
/**
* 讀取文件內容
*
* @param file
* 文件對象
* @param line
* 是否換行(true:換行,false:非換行),默認換行
* @return 文件內容
* @throws IOException
*/
public static final String readString(File file) {
return readString(file, true);
}
/**
* 讀取文件內容
*
* @param file
* 文件對象
* @param line
* 是否換行(true:換行,false:非換行)
* @return 文件內容
* @throws IOException
*/
public static final String readString(File file, boolean line) {
return readString(file, null, line);
}
/**
* 讀取文件內容
*
* @param file
* 文件對象
* @param encoding
* 編碼
* @return 文件內容
* @throws IOException
*/
public static final String readString(File file, String encoding) {
return readString(file, encoding, true);
}
/**
* 讀取文件內容
*
* @param file
* 文件對象
* @param encoding
* 編碼
* @param line
* 是否換行(true:換行,false:非換行)
* @return 文件內容
* @throws IOException
*/
public static final String readString(File file, String encoding, boolean line) {
InputStream in = null;
try {
in = FileUtils.openInputStream(file);
return readString(in, encoding, line);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(in);
}
}
/**
* 讀取文件內容
*
* @param input
* 輸入流
* @param encoding
* 編碼
* @param line
* 是否換行(true:換行,false:非換行)
* @return 文件內容
* @throws IOException
*/
public static final String readString(InputStream input, String encoding, boolean line) {
InputStreamReader reader = null;
try {
if (CheckUtil.isNull(encoding)) {
encoding = "UTF-8";
}
// if (encoding == null) {
// return readString(input, line);
// } else {
// reader = new InputStreamReader(input, encoding);
// return readString(reader, line);
// }
reader = new InputStreamReader(input, encoding);
return readString(reader, line);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(reader);
}
}
/**
* 讀取文件內容
*
* @param input
* 輸入流
* @param line
* 是否換行(true:換行,false:非換行)
* @return 文件內容
* @throws IOException
*/
public static final String readString(InputStream input, boolean line) {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(input);
return readString(reader, line);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(reader);
}
}
/**
* 讀取文件內容
*
* @param input
* 輸入流
* @param line
* 是否換行(true:換行,false:非換行)
* @return 文件內容
* @throws IOException
*/
public static final String readString(Reader input, boolean line) {
BufferedReader reader = null;
try {
StringBuffer sb = new StringBuffer();
reader = new BufferedReader(input);
String lineString = reader.readLine();
lineString = IOUtils.readFirstLine(lineString);
if (line) {
while (lineString != null) {
if (CheckUtil.isNotNull(sb.toString())) {
sb.append(IOUtils.LINE_SEPARATOR);
}
sb.append(lineString);
lineString = reader.readLine();
}
} else {
while (lineString != null) {
sb.append(lineString);
lineString = reader.readLine();
}
}
return sb.toString();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(reader);
}
}
/**
*
* @param file
* 文件對象
* @param maxLine
* 最大行
* @return
*/
public static final String readLine(File file, long maxLine) {
return readLine(file, "UTF-8", true, maxLine);
}
/**
*
* @param file
* 文件對象
* @param encoding
* 編碼
* @param maxLine
* 最大行
* @return
*/
public static final String readLine(File file, String encoding, long maxLine) {
return readLine(file, encoding, true, maxLine);
}
/**
* 讀取文件內容
*
* @param file
* 文件對象
* @param encoding
* 編碼
* @param line
* 是否換行(true:換行,false:非換行)
* @return 文件內容
* @throws IOException
*/
public static final String readLine(File file, String encoding, boolean line, long maxLine) {
InputStream in = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
StringBuffer sb = new StringBuffer();
in = FileUtils.openInputStream(file);
isr = new InputStreamReader(in, encoding);
br = new BufferedReader(isr);
// 臨時行數
long tmpLine = 0;
String lineString = br.readLine();
tmpLine++;
lineString = IOUtils.readFirstLine(lineString);
if (line) {
while (lineString != null) {
if (maxLine > 0 && tmpLine > maxLine) {
break;
}
if (CheckUtil.isNotNull(sb.toString())) {
sb.append(IOUtils.LINE_SEPARATOR);
}
sb.append(lineString);
lineString = br.readLine();
tmpLine++;
}
} else {
while (lineString != null) {
if (maxLine > 0 && tmpLine > maxLine) {
break;
}
sb.append(lineString);
lineString = br.readLine();
tmpLine++;
}
}
return sb.toString();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(isr);
IOUtils.closeQuietly(br);
}
}
// readLines
// -----------------------------------------------------------------------
public static final <T extends Collection<String>> void readLines(T t, File file) {
readLines(t, file, null);
}
public static final <T extends Collection<String>> void readLines(T t, File file, String encoding) {
InputStream in = null;
try {
in = FileUtils.openInputStream(file);
readLines(t, in, encoding);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(in);
}
}
public static final <T extends Collection<String>> void readLines(T t, InputStream input, String encoding) {
try {
if (encoding == null) {
readLines(t, input);
} else {
InputStreamReader reader = new InputStreamReader(input, encoding);
readLines(t, reader);
}
} catch (Exception e) {
throw new ServiceException(e);
}
}
public static final <T extends Collection<String>> void readLines(T t, InputStream input) {
InputStreamReader reader = new InputStreamReader(input);
readLines(t, reader);
}
public static final <T extends Collection<String>> void readLines(T t, Reader input) {
try {
Collection<String> coll = getColl(t);
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
line = IOUtils.readFirstLine(line);
while (line != null) {
coll.add(line);
line = reader.readLine();
}
} catch (Exception e) {
throw new ServiceException(e);
}
}
// readLinesCountI
// -----------------------------------------------------------------------
public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(File file, ReadLinesCallI<T> call) {
return readLinesCountI(file, null, call);
}
public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(File file, String encoding, ReadLinesCallI<T> call) {
InputStream in = null;
try {
in = FileUtils.openInputStream(file);
return readLinesCountI(in, encoding, call);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(in);
}
}
public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(InputStream input, String encoding, ReadLinesCallI<T> call) {
try {
if (encoding == null) {
return readLinesCountI(input, call);
} else {
InputStreamReader reader = new InputStreamReader(input, encoding);
return readLinesCountI(reader, call);
}
} catch (Exception e) {
throw new ServiceException(e);
}
}
public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(InputStream input, ReadLinesCallI<T> call) {
InputStreamReader reader = new InputStreamReader(input);
return readLinesCountI(reader, call);
}
/**
* 讀取大文件
*
* @param input
* 輸入流
* @param call
* 回調
* @return {@code KV<總行數,實際行數>}
* @throws IOException
*/
public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(Reader input, ReadLinesCallI<T> call) {
long totalLineNum = 0;
long lineNum = 0;
try {
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
line = IOUtils.readFirstLine(line);
long startLineNum = call.getStartLineNum();
long endLineNum = call.getEndLineNum();
String linePrev = null;
String lineNext = null;
boolean first = true;
while (line != null) {
totalLineNum++;
if (first) {
// 這里只讀取一次
// 讀取下下一行
lineNext = reader.readLine();
first = false;
}
// 是否中斷
if (call.interrupt(linePrev, line, lineNext, totalLineNum)) {
break;
}
if (startLineNum <= totalLineNum && (endLineNum <= 0 || endLineNum >= totalLineNum)) {
// 開始/結束行區間數據
KV<String, Boolean> kv = call.changeLine(linePrev, line, lineNext, totalLineNum);
if (kv != null) {
line = kv.getK();
boolean filter = kv.getV();
// 是否過慮
if (filter) {
lineNum++;
}
}
}
// 賦值上一行
linePrev = line;
// 讀取下一行
line = lineNext;
if (line != null) {
// 讀取下下一行
lineNext = reader.readLine();
}
}
} catch (Exception e) {
throw new ServiceException(e);
}
return KV.with(totalLineNum, lineNum);
}
// readLinesI
// -----------------------------------------------------------------------
public static final <T extends Collection<String>> T readLinesI(File file, ReadLinesCallI<T> call) {
return readLinesI(file, null, call);
}
public static final <T extends Collection<String>> T readLinesI(File file, String encoding, ReadLinesCallI<T> call) {
InputStream in = null;
try {
in = FileUtils.openInputStream(file);
return readLinesI(in, encoding, call);
} catch (Exception e) {
throw new ServiceException(e);
} finally {
IOUtils.closeQuietly(in);
}
}
public static final <T extends Collection<String>> T readLinesI(InputStream input, String encoding, ReadLinesCallI<T> call) {
try {
if (encoding == null) {
return readLinesI(input, call);
} else {
InputStreamReader reader = new InputStreamReader(input, encoding);
return readLinesI(reader, call);
}
} catch (Exception e) {
throw new ServiceException(e);
}
}
public static final <T extends Collection<String>> T readLinesI(InputStream input, ReadLinesCallI<T> call) {
InputStreamReader reader = new InputStreamReader(input);
return readLinesI(reader, call);
}
/**
* 把文件中每一行設置到集合中(never return null)
*
* @param input
* @param call
* @return
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static final <T extends Collection<String>> T readLinesI(Reader input, ReadLinesCallI<T> call) {
try {
T t = call.getObj();
Collection<String> coll = getColl(t);
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
line = IOUtils.readFirstLine(line);
long startLineNum = call.getStartLineNum();
long endLineNum = call.getEndLineNum();
long totalLineNum = 0;
String linePrev = null;
String lineNext = null;
boolean first = true;
while (line != null) {
totalLineNum++;
if (first) {
// 這里只讀取一次
// 讀取下下一行
lineNext = reader.readLine();
first = false;
}
// 是否中斷
if (call.interrupt(linePrev, line, lineNext, totalLineNum)) {
break;
}
if (startLineNum <= totalLineNum && (endLineNum <= 0 || endLineNum >= totalLineNum)) {
// 開始/結束行區間數據
KV<String, Boolean> kv = call.changeLine(linePrev, line, lineNext, totalLineNum);
if (kv != null) {
line = kv.getK();
boolean filter = kv.getV();
// 是否過慮
if (filter) {
coll.add(line);
}
}
}
// 賦值上一行
linePrev = line;
// 讀取下一行
line = lineNext;
if (line != null) {
// 讀取下下一行
lineNext = reader.readLine();
}
}
return (T) coll;
} catch (Exception e) {
throw new ServiceException(e);
}
}
// readLinesBatchI
// -----------------------------------------------------------------------
public static final <T extends Collection<String>> List<T> readLinesBatchI(File file, ReadLinesCallI<T> call, ReadLinesBatchCallI<T> batchI) {
return readLinesBatchI(file, null, call, batchI);
}
/**
* 把文件中每一行設置到批量集合中(never return null)
*
* @param file
* @param encoding
* @param call
* @param batchI
* @return
* @throws IOException
*/
public static final <T extends Collection<String>> List<T> readLinesBatchI(File file, String encoding, ReadLinesCallI<T> call, ReadLinesBatchCallI<T> batchI) {
List<T> lists = new ArrayList<T>();
// 獲取總數
KV<Long, Long> kv = readLinesCountI(file, call);
long size = kv.getV();
if (size > 0) {
long start = System.currentTimeMillis();
long batchSize = batchI.getBatchSize();
if (batchSize > 1) {
long preNum = size / batchSize;
long modNum = size % batchSize;
// 100/10=10
for (long i = 1; i <= preNum; i++) {
call.setStartLineNum((i - 1) * batchSize + 1);
call.setEndLineNum(i * batchSize);
setBatchCollI(file, encoding, call, batchI, lists);
}
if (modNum == 0) {
} else {
// 11/3=3...2
// 設置剩余的量
call.setStartLineNum(preNum * batchSize + 1);
call.setEndLineNum(size);
setBatchCollI(file, encoding, call, batchI, lists);
}
} else {
setBatchCollI(file, encoding, call, batchI, lists);
}
long end = System.currentTimeMillis();
long x = (end - start) / 1000;
long y = (end - start) % 1000;
logger.debug("全部讀取完畢...,總執行時間:" + (end - start) + "毫秒," + x + "." + (y < 100 ? "0" + y : y) + "秒");
}
return lists;
}
/**
* 批量設置集合
*
* @param file
* @param encoding
* @param call
* @param batchI
* @param lists
* @throws IOException
*/
private static <T extends Collection<String>> void setBatchCollI(File file, String encoding, ReadLinesCallI<T> call, ReadLinesBatchCallI<T> batchI, List<T> lists) {
logger.debug("正在讀取..." + (call.getEndLineNum() <= 0 ? "全部數據" : "[" + call.getStartLineNum() + "-" + call.getEndLineNum() + "]行數據"));
long start = System.currentTimeMillis();
T t = readLinesI(file, encoding, call);
if (batchI.isCallBatchColl()) {
batchI.callBatchColl(t);
} else {
lists.add(t);
}
long end = System.currentTimeMillis();
long x = (end - start) / 1000;
long y = (end - start) % 1000;
logger.debug("讀取完畢..." + (call.getEndLineNum() <= 0 ? "全部數據" : "[" + call.getStartLineNum() + "-" + call.getEndLineNum() + "]行數據") + ",執行時間:" + (end - start) + "毫秒," + x + "." + (y < 100 ? "0" + y : y) + "秒");
}
/**
* 獲取對應的集合類型
*
* @param t
* @return
* @throws IOException
*/
private static <T extends Collection<String>> Collection<String> getColl(T t) {
Collection<String> coll = null;
if (t instanceof List) {
coll = (List<String>) t;
} else if (t instanceof Set) {
coll = (Set<String>) t;
} else {
throw new ServiceException("不支持的返回類型" + t);
}
return coll;
}
/**
* 查找沖突jar包
*
* @param path
* 所要查找的JAR包的目錄
* @param className
* 要查詢的class,要帶包名的類名
* @return
*/
public static final List<String> findClassConflictJar(String path, String className) {
List<String> results = new ArrayList<String>();
className = className.replace('.', '/') + ".class";
findClassConflictJar(path, className, results);
return results;
}
/**
* 查找沖突jar包
*
* @param path
* 所要查找的JAR包的目錄
* @param className
* 要查詢的class,要帶包名的類名
* @param results
* 沖突的jar文件路徑集合
*/
private static final void findClassConflictJar(String path, String className, List<String> results) {
path = changePathSeparator(path, ConstantForEnum.ChangePathLastSeparator.ADD_AFTER);
File file = new File(path);
if (!file.exists()) {
logger.warn("文件[" + file.getAbsolutePath() + "]不存在");
return;
}
if (file.isFile()) {
logger.warn("文件[" + file.getAbsolutePath() + "]不是目錄,強制返回結果");
return;
}
String[] filelist = file.list();
if (filelist == null) {
logger.warn("文件[" + file.getAbsolutePath() + "]中沒有任何文件,強制返回結果");
return;
}
for (int i = 0; i < filelist.length; i++) {
String filePath = filelist[i];
File temp = new File(path + filePath);
// if ((temp.isDirectory() && !temp.isHidden() && temp.exists())) {
if (temp.isDirectory()) {
findClassConflictJar(path + filePath, className, results);
} else {
if (filePath.toLowerCase().endsWith("jar")) {
try {
java.util.jar.JarFile jarfile = new java.util.jar.JarFile(path + filePath);
for (Enumeration<JarEntry> e = jarfile.entries(); e.hasMoreElements();) {
String name = e.nextElement().toString();
if (name.equals(className) || name.indexOf(className) > -1) {
// System.out.println(path + filePath);
results.add(path + filePath);
}
jarfile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
// /**
// * 查找沖突jar包
// *
// * @param objPath
// * jar文件或目錄對象
// * @param jarClass
// * 每個jar路徑對應的class集合
// * @param classResult
// * 所有class(包路徑)對應的jar文件路徑
// * @param conflictClass
// * 沖突class(包路徑)對應的jar文件路徑
// */
// @SuppressWarnings("unchecked")
// public static final void findJarConflictClass(Object objPath, Map<String, Set<JarClass>> jarClassResult, Map<String, Set<String>> classResult, Map<String, Set<String>> conflictResult) {
@SuppressWarnings("unchecked")
public static final void findJarConflictClass(JarParams params) {
Collection<String> values = null;
Object objPath = params.getObjPath();
if (CheckUtil.isNull(objPath)) {
// 如果沒有設置objPath,則默認path為objPath值
objPath = params.getPath();
}
if (objPath instanceof String) {
// 此處不會被執行
values = new HashSet<String>();
values.add(String.valueOf(objPath));
} else if (objPath instanceof Collection) {
values = ((Collection<String>) objPath);
} else if (objPath instanceof String[]) {
values = Arrays.asList((String[]) objPath);
}
if (values == null || values.size() == 0) {
logger.warn("jar文件或目錄對象數據格式不正確");
return;
}
// 循環寫
Iterator<String> it = values.iterator();
while (it.hasNext()) {
// doFindJarConflictClass(it.next(), jarClassResult, classResult, conflictResult);
// 設置path值
params.setPath(it.next());
doFindJarConflictClass(params);
}
}
// /**
// * 查找沖突jar包
// *
// * @param path
// * jar文件或目錄路徑
// * @param jarClass
// * 每個jar路徑對應的class集合
// * @param classResult
// * 所有class(包路徑)對應的jar文件路徑
// * @param conflictClass
// * 沖突class(包路徑)對應的jar文件路徑
// */
// public static final void findJarConflictClass(String path, Map<String, Set<JarClass>> jarClassResult, Map<String, Set<String>> classResult, Map<String, Set<String>> conflictResult) {
private static final void doFindJarConflictClass(final JarParams params) {
final String path = changePathSeparator(params.getPath(), ConstantForEnum.ChangePathLastSeparator.ADD_AFTER);
final Map<String, Set<JarClass>> jarClassResult = params.getJarClassResult();
final Map<String, Set<String>> classResult = params.getClassResult();
final Map<String, Set<String>> conflictResult = params.getConflictResult();
File file = new File(path);
if (!file.exists()) {
logger.warn("文件[" + file.getAbsolutePath() + "]不存在");
return;
}
if (file.isFile()) {
logger.warn("文件[" + file.getAbsolutePath() + "]不是目錄,強制返回結果");
return;
}
final String[] filelist = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// System.out.println(dir + "," + name + "," + FilenameUtils.getExtension(name));
String extension = FilenameUtils.getExtension(name);
if (CheckUtil.isNotNull(extension)) {
if ("jar".equals(extension.toLowerCase())) {
return true;
}
}
return false;
}
});
if (filelist == null || filelist.length == 0) {
logger.warn("文件[" + file.getAbsolutePath() + "]中沒有任何文件,強制返回結果");
return;
}
for (int i = 0; i < filelist.length; i++) {
final String filePath = filelist[i];
doJarClass(params, path, jarClassResult, classResult, conflictResult, filePath);
}
}
/**
* 處理jar中的class
*
* @param params
* @param path
* @param jarClassResult
* @param classResult
* @param conflictResult
* @param filePath
*/
private static final void doJarClass(final JarParams params, final String path, final Map<String, Set<JarClass>> jarClassResult, final Map<String, Set<String>> classResult, final Map<String, Set<String>> conflictResult, final String filePath) {
File temp = new File(path + filePath);
// if ((temp.isDirectory() && !temp.isHidden() && temp.exists())) {
if (temp.isDirectory()) {
// findJarConflictClass(path + filePath, jarClassResult, conflictResult, classResult);
doFindJarConflictClass(params);
} else {
try {
String jarPath = changePathSeparator(path + filePath);
// System.out.println(jarPath);
Set<JarClass> jarClasss = null;
// 可以為null
if (jarClassResult != null) {
jarClasss = jarClassResult.get(jarPath);
if (jarClasss == null) {
// 不存在
jarClasss = new HashSet<JarClass>();
jarClassResult.put(jarPath, jarClasss);
}
}
java.util.jar.JarFile jarfile = new java.util.jar.JarFile(path + filePath);
for (Enumeration<JarEntry> e = jarfile.entries(); e.hasMoreElements();) {
// 獲取jar文件
String classPath = e.nextElement().toString();
String extension = FilenameUtils.getExtension(classPath);
String fullPath = jarPath + "!" + classPath;
// 是否是class文件
if ("class".equals(extension.toLowerCase())) {
// 轉換為class包
int index = classPath.lastIndexOf(".");
String prefixClassName = classPath;
if (index > -1) {
prefixClassName = classPath.substring(0, index);
}
String className = prefixClassName.replaceAll("/", ".");
// 添加class
Set<String> classJars = classResult.get(className);
if (classJars == null) {
classJars = new HashSet<String>();
classResult.put(className, classJars);
} else {
// 沖突了
Set<String> classConflictJars = conflictResult.get(className);
if (classConflictJars == null) {
classConflictJars = new HashSet<String>();
conflictResult.put(className, classConflictJars);
}
// 添加jar文件(會自動去重)
classConflictJars.add(jarPath);
// 添加沖突的class對應的所有jar文件路徑
classConflictJars.addAll(classJars);
}
classJars.add(jarPath);
if (jarClasss != null) {
JarClass jarClass = new JarClass();
// 設置jar屬性
jarClass.setFileDir(path);
jarClass.setClassPath(classPath);
jarClass.setClassName(className);
jarClass.setFullPath(fullPath);
jarClasss.add(jarClass);
}
} else {
logger.debug("文件[" + fullPath + "]不是class文件,繼續查找");
}
}
jarfile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 寫文件
*
* @param filePath
* 文件路徑
* @param content
* 文件內容
* @throws IOException
*/
public static final void write(String filePath, String content) {
write(new File(filePath), content, "UTF-8");
}
/**
* 寫文件
*
* @param filePath
* 文件路徑
* @param content
* 文件內容
* @param encoding
* 編碼
* @throws IOException
*/
public static final void write(String filePath, String content, String encoding) {
write(new File(filePath), content, encoding);
}
/**
* 寫文件
*
* @param filePath
* 文件對象
* @param content
* 文件內容
* @throws IOException
*/
public static final void write(File file, String content) {
write(file, content, null);
}
/**
* 寫文件
*
* @param filePath
* 文件對象
* @param content
* 文件內容
* @param encoding
* 編碼
* @throws IOException
*/
public static final void write(File file, String content, String encoding) {
try {
createFolderOrFile(file, false);
if (file == null)
return;
if (CheckUtil.isNull(content)) {
content = "";
}
if (CheckUtil.isNull(encoding)) {
encoding = "UTF-8";
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
OutputStreamWriter writer = new OutputStreamWriter(bos, encoding);
writer.write(content);
writer.flush();
writer.close();
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 寫文件
*
* @param content
* 文件字節內容
* @param encoding
* 編碼
* @throws IOException
*/
public static void write(byte[] content, File outFile) {
FileOutputStream fout = null;
try {
createFolderOrFile(outFile);
fout = new FileOutputStream(outFile);
fout.write(content);
fout.flush();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
if (fout != null) {
try {
fout.close();
} catch (Exception e2) {
}
}
}
}
/**
* 將圖片文件轉化為字節數組字符串,并對其進行Base64編碼處理
*
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @return 頁面地址
*/
public static final String GetImageStr(String imgFilePath) {
byte[] data = null;
BufferedInputStream bis = null;
// 讀取圖片字節數組
try {
bis = new BufferedInputStream(new FileInputStream(imgFilePath));
data = new byte[bis.available()];
bis.read(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64編碼過的字節數組字符串
return encoder.encode(data);
}
/**
* 對字節數組字符串進行Base64解碼并生成圖片
*
* @author 張軍
* @date 2015-11-03 21:59:00
* @modifiyNote
* @version 1.0
* @return 頁面地址
*/
public static final boolean GenerateImage(String imgStr, String imgFilePath) {
// 圖像數據為空
if (imgStr == null)
return false;
if (imgStr.indexOf("data:image/jpeg;base64,") != -1) {
imgStr = imgStr.substring("data:image/jpeg;base64,".length());
}
BASE64Decoder decoder = new BASE64Decoder();
BufferedOutputStream bos = null;
try {
// Base64解碼
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 調整異常數據
bytes[i] += 256;
}
}
// 生成jpeg圖片
bos = new BufferedOutputStream(new FileOutputStream(imgFilePath));
bos.write(bytes);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
本文為張軍原創文章,轉載無需和我聯系,但請注明來自張軍的軍軍小站,個人博客http://www.dlhighland.cn
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

