字節流存儲文件以及解、壓縮工具類
阿新 • • 發佈:2019-01-26
eat source read bis imp next raw nco 異常
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.*;
/**
* 文件和目錄相關
*
*/
public abstract class ToolDirFile {
private static final Log log = Log.getLog(ToolDirFile.class);
private static String libPath;
private static String classesPath;
/**
* 獲取lib目錄
*
* @return
*/
public static String getLibPath() {
if (libPath == null) {
libPath = PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "lib";
}
return libPath;
}
/**
* 獲取classes目錄
*
* @return
*/
public static String getClassesPath() {
if (classesPath == null) {
/**
* 1.兼容運行模式 直接運行 JFinalConfig 中的 main 方法 maven: 直接運行 JFinalConfig 中的
* main 方法 maven: jetty:run maven: tomcat7:run
*/
// classesPath = PathKit.getRootClassPath();
/**
* 2.兼容jboss war部署
*/
classesPath = PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "classes";
}
return classesPath;
}
/**
* 獲取classes路徑
*
* @return
*/
@SuppressWarnings("rawtypes")
public static String getClassesPath(Class classs) {
String classRootPath = classs.getClassLoader().getResource("").getFile();
try {
classRootPath = java.net.URLDecoder.decode(classRootPath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
if(log.isErrorEnabled()) log.error("初始化加載sql:獲取classRootPath異常");
}
return classRootPath;
}
/**
* 獲取當前代碼所在行
*
* @return
*/
public static String getLineNumber() {
StackTraceElement ste = new Throwable().getStackTrace()[1];
return ste.getFileName() + ": Line " + ste.getLineNumber();
}
/**
* 獲取目錄下的文件名稱,不包含子目錄名稱
*
* @param dirPath
* @return
*/
public static List<String> getDirFileNames(String dirPath) {
List<String> nameList = new ArrayList<String>();
File file = new File(dirPath);
File[] files = file.listFiles();
for (File fileTemp : files) {
if (!fileTemp.isDirectory()) {
nameList.add(fileTemp.getName());
}
}
return nameList;
}
/**
* 復制文件夾或文件
*
* @param source
* @param target
* @throws IOException
*/
public static void copyDir(String source, String target) throws IOException {
(new File(source)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(source)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 復制文件
copyFile(file[i], new File(target + file[i].getName()));
}
if (file[i].isDirectory()) {
// 復制目錄
String sourceDir = source + File.separator + file[i].getName();
String targetDir = target + File.separator + file[i].getName();
copyDirectiory(sourceDir, targetDir);
}
}
}
/**
* copy文件或目錄
*
* @param source
* @param target
*/
public static void lovecopy(String source, String target) {
// (new File(url2)).mkdirs();
File f = new File(target);
if (!f.exists()) {
f.mkdirs();
}
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(source)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 復制文件
try {
copyFile(file[i], new File(target + file[i].getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
if (file[i].isDirectory()) {
// 復制目錄
String sourceDir = source + File.separator + file[i].getName();
String targetDir = target + File.separator + file[i].getName();
try {
copyDirectiory(sourceDir, targetDir);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 復制文件
*
* @param sourceFile
* @param targetFile
* @throws IOException
*/
public static void copyFile(File sourceFile, File targetFile) throws IOException {
// 新建文件輸入流並對它進行緩沖
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件輸出流並對它進行緩沖
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 緩沖數組
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此緩沖的輸出流
outBuff.flush();
// 關閉流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
/**
* 復制文件夾
*
* @param sourceDir
* @param targetDir
* @throws IOException
*/
public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
// 新建目標目錄
(new File(targetDir)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile = file[i];
// 目標文件
File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 準備復制的源文件夾
String dir1 = sourceDir + "/" + file[i].getName();
// 準備復制的目標文件夾
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
/**
* 檢查目錄是否存在,如果不存在就創建目錄
*
* @param dirPath
*/
public static void createDirectory(String dirPath) {
File file = new File(dirPath);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 刪除文件或者目錄
*
* @param file
*/
public static void delete(File file) {
if (file != null && file.exists()) {
if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0, length = files.length; i < length; i++) {
delete(files[i]);
}
} else {
file.delete();
}
}
}
/**
* 文件下載
*
* @param response
* @param fileName
* @param filePath
* @throws IOException
*/
public static void download(HttpServletResponse response, String fileName, String filePath) throws IOException {
FileInputStream fis = null;
BufferedInputStream buff = null;
try {
File file = new File(filePath);
response.setContentType("application/x-msdownload");// 設置response的編碼方式
response.setContentLength((int) file.length());// 寫明要下載的文件的大小
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes(ToolString.encoding), "iso-8859-1")); // 解決中文亂碼
// 讀出文件到i/o流
fis = new FileInputStream(file);
buff = new BufferedInputStream(fis);
byte[] bytes = new byte[1024];// 相當於我們的緩存
long k = 0;// 該值用於計算當前實際下載了多少字節
OutputStream os = response.getOutputStream();// 從response對象中得到輸出流,準備下載
// 開始循環下載
while (k < file.length()) {
int j = buff.read(bytes, 0, 1024);
k += j;
os.write(bytes, 0, j);// 將b中的數據寫到客戶端的內存
}
os.flush();// 將寫入到客戶端的內存的數據,刷新到磁盤
buff.close();
buff = null;
fis.close();
fis = null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (buff != null) {
buff.close();
buff = null;
}
if (fis != null) {
fis.close();
fis = null;
}
}
}
/**
* 創建文件
*
* @param savePath
* 保存路徑
* @param content
* 文件內容
*/
public static void createFile(String savePath, String content) {
try {
File file = new File(savePath);
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(content);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 指定位置開始寫入文件
* @param outPath 輸出文件的路徑(路徑+文件名)
* @param tempFile 輸入文件
* 描述 :把目標文件的指針,移到文件末尾,然後把分片文件追加進去,實現文件合並
*/
public static void writeFile(String outPath, File tempFile) {
RandomAccessFile raFile = null;
BufferedInputStream inputStream=null;
try{
File dirFile = new File(outPath);
raFile = new RandomAccessFile(dirFile, "rw"); //以讀寫的方式打開目標文件
raFile.seek(raFile.length());
inputStream = new BufferedInputStream(new FileInputStream(tempFile));
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
raFile.write(buf, 0, length);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if (inputStream != null) {
inputStream.close();
}
if (raFile != null) {
raFile.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
/***
* 壓縮GZip
*
* @param data
* @return
*/
public static byte[] gZip(byte[] data) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.finish();
gzip.close();
b = bos.toByteArray();
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
/***
* 解壓GZip
*
* @param data
* @return
*/
public static byte[] unGZip(byte[] data) {
byte[] b = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
GZIPInputStream gzip = new GZIPInputStream(bis);
byte[] buf = new byte[1024];
int num = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((num = gzip.read(buf, 0, buf.length)) != -1) {
baos.write(buf, 0, num);
}
b = baos.toByteArray();
baos.flush();
baos.close();
gzip.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
/***
* 壓縮Zip
*
* @param data
* @return
*/
public static byte[] zip(byte[] data) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);
ZipEntry entry = new ZipEntry("zip");
entry.setSize(data.length);
zip.putNextEntry(entry);
zip.write(data);
zip.closeEntry();
zip.close();
b = bos.toByteArray();
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
/***
* 解壓Zip
*
* @param data
* @return
*/
public static byte[] unZip(byte[] data) {
byte[] b = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ZipInputStream zip = new ZipInputStream(bis);
while (zip.getNextEntry() != null) {
byte[] buf = new byte[1024];
int num = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((num = zip.read(buf, 0, buf.length)) != -1) {
baos.write(buf, 0, num);
}
b = baos.toByteArray();
baos.flush();
baos.close();
}
zip.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
/***
* 壓縮BZip2
*
* @param data
* @return
*/
public static byte[] bZip2(byte[] data) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BZip2CompressorOutputStream bzip2 = new BZip2CompressorOutputStream(bos);
bzip2.write(data);
bzip2.flush();
bzip2.close();
b = bos.toByteArray();
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
/***
* 解壓BZip2
*
* @param data
* @return
*/
public static byte[] unBZip2(byte[] data) {
byte[] b = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BZip2CompressorInputStream bzip2 = new BZip2CompressorInputStream(bis);
byte[] buf = new byte[1024];
int num = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((num = bzip2.read(buf, 0, buf.length)) != -1) {
baos.write(buf, 0, num);
}
b = baos.toByteArray();
baos.flush();
baos.close();
bzip2.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
private static BASE64Decoder b= new BASE64Decoder();
private static LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
static {
map.put("image/jpeg", ".jpg");
map.put("image/gif", ".gif");
map.put("image/png", ".png");
map.put("video/mp4", ".mp4");
map.put("video/quicktime", ".mov");
map.put("audio/amr",".mp3");
}
public static String getSuffix(String fileType) {
return map.get(fileType);
}
public static void writeFile(String filePath,InputStream is) {
FileOutputStream fos=null;
BufferedOutputStream bos=null;
try{
fos=new FileOutputStream(filePath);
bos =new BufferedOutputStream(fos);
int n = 0;// 每次讀取的字節長度
byte[] bb = new byte[1024];// 存儲每次讀取的內容
while ((n = is.read(bb)) != -1) {
bos.write(bb, 0, n);// 將讀取的內容,寫入到輸出流當中
}
bos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bos!=null)bos.flush();
if(fos!=null)fos.close();
if(bos!=null)bos.close();
if(is!=null)is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String getFilePath(String fileType) {
String rootPath= PropKit.get("file.server.path");
String path="";
Calendar c=Calendar.getInstance();
if(StrKit.notBlank(fileType)){
path+=File.separator+fileType;
}
path+=File.separator+ DateKit.toStr(new Date(),"yyyy\\MM");
File file=new File(rootPath+path);
if(file!=null && !file.exists()){
file.mkdirs();
}
return path;
}
public static File createFile(String pathname) {
try {
File file = new File(pathname);
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
file.createNewFile();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static File base64ToFile(String base64,String fileName){
File file=null;
FileOutputStream o=null;
try {
if(StrKit.notBlank(base64)){
file=createFile(fileName);
byte[] image = b.decodeBuffer(base64);
o = new FileOutputStream(file);
o.write(image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(o!=null)o.flush();
if(o!=null)o.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
/**
*
* createFolder:(在指定文件夾下創建以月份命名的文件夾).
* @author sjh
* @param dir <br/>
*/
public static String createDir(String dirNameParent){
File dirParent=new File(dirNameParent);
if (!dirParent.exists()) {
System.out.println("目錄" + dirNameParent + "不存在,正在嘗試創建目錄~");
dirParent.mkdirs();
}
if (!dirNameParent.endsWith(File.separator) && !dirNameParent.endsWith("/")) {
dirNameParent = dirNameParent + File.separator;
}
String dirName=DateFormatUtil.yyyyMMFormat.format(new Date());
dirName = dirNameParent + dirName;
File dir=new File(dirName);
dirName+="/";
if(dir.exists()){
System.out.println("目錄" + dirName + "已存在,無需創建~");
return dirName;
}else{
if (dir.mkdirs()) {
System.out.println("創建目錄" + dirName + "成功!");
return dirName;
} else {
System.out.println("創建目錄" + dirName + "失敗!");
return null;
}
}
}
/**
* 獲得指定文件的byte數組
*/
public static byte[] getBytes(File file){
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
/**
* 根據byte數組,生成文件
*/
public static File getFile(byte[] bfile, String filePath,String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if(!dir.exists()&&dir.isDirectory()){//判斷文件目錄是否存在
dir.mkdirs();
}
file = new File(filePath+"\\"+fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return file;
}
}
字節流存儲文件以及解、壓縮工具類