文件操作工具类FileUtil
生活随笔
收集整理的這篇文章主要介紹了
文件操作工具类FileUtil
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
分享一個文件處理的工具類,依賴如下:
<dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.10.5</version></dependency>工具類如下:
package com.leo.demo.othertest;import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tools.tar.TarEntry; import org.apache.tools.tar.TarInputStream;/*** 文件操作工具類*/ public class FileUtil {private static Log log = LogFactory.getLog(FileUtil.class);private static int FILE_BUFFER_SIZE = 1024*64;private String fileName = null;private String mode = null;private RandomAccessFile file = null;private String lineSeparator = System.getProperty("line.separator");public FileUtil() {}/*** 傳入文件名稱、文件打開模式,初始化文件操作公用類* @param fileName 文件名稱* @param mode 文件打開模式* @return*/public FileUtil(String fileName, String mode) {this.fileName = fileName;this.mode = mode;}/*** 設(shè)置文件操作公用類中的文件名稱、文件打開模式參數(shù)* @param fileName 文件名稱* @param mode 文件打開模式* @return*/public void setFileInfo(String fileName, String mode) {this.fileName = fileName;this.mode = mode;}/*** 設(shè)置文件操作公用類中的文件名稱參數(shù)* @param fileName 文件名稱* @return*/public void setFileName(String fileName) {this.fileName = fileName;}/*** 設(shè)置文件操作公用類中的文件名稱* @return String 文件名稱*/public String getFileName() {return this.fileName;}/*** 設(shè)置文件操作公用類中的文件打開模式參數(shù)* @param mode 文件打開模式* @return*/public void setMode(String mode) {this.mode = mode;}/*** 獲取文件操作公用類中的文件打開模式參數(shù)* @param* @return mode 文件打開模式*/public String getMode() {return mode;}/*** 通過傳入的文件名以及文件打開模式打開指定文件* @param fileName 文件名稱* @param mode 文件打開模式* @return* @throws IOException*/public void open(String fileName, String mode) throws IOException {this.fileName = fileName;this.mode = mode;open();}/*** 通過已賦值參數(shù),打開相應(yīng)文件* @param* @return* @throws IOException*/public void open() throws IOException {if( fileName==null || fileName.length()==0 ) {log.info("文件名為空,請核實!");throw(new IOException("文件名為空,請核實!"));}file = new RandomAccessFile(fileName, mode);}/*** 讀取已打開文件的下一行字符串* @param* @return String 文件行數(shù)據(jù)* @throws IOException*/public String getLine() throws IOException {String line = null;if( file!=null ) {line = file.readLine();if( line!=null ) {line = new String(line.getBytes("ISO8859-1"), "gb2312");}}return line;}/*** 讀取已打開文件的下一行字符串* @param* @return String 文件行數(shù)據(jù)* @throws IOException*/public int read(byte[] buffer, int offset, int len) throws IOException {if( file!=null ) {return file.read(buffer, offset, len);}return 0;}/*** 取已打開文件的大小* @param* @return long 文件大小* @throws IOException*/public long length() throws IOException {long len = 0;if( file!=null ) {len = file.length();}return len;}/*** 在已打開文件寫入指定字符串* @param* @return String 字符串* @throws IOException*/public void write(String line) throws IOException {if( file!=null && line!=null ) {file.write(line.getBytes());}}/*** 在已打開文件寫入指定字符串* @param* @return String 字符串* @throws IOException*/public void write(byte[] buffer, int offset, int length) throws IOException {if( file!=null ) {file.write(buffer, offset, length);}}/*** 在已打開文件中將指定字符串作為一行寫入* @param* @return String 字符串* @throws IOException*/public void writeLine(String line) throws IOException {if( file!=null && line!=null ) {String newline =line+ lineSeparator;file.write(newline.getBytes());}}/*** 數(shù)據(jù)刷新* @param* @return* @throws IOException*/public void flush() throws IOException {if( file!=null ) {FileChannel fd = file.getChannel();fd.force(true);}}/*** 關(guān)閉已打開文件* @param* @return* @throws IOException*/public void close() throws IOException {if( file!=null ) {file.close();}}/*** 把指定文件從源目錄移到指定目標目錄中* @param srcPath 源文件目錄* @param descPath 目標文件目錄* @param fileName 源文件名稱* @return* @throws IOException*/public static void moveFile(String srcPath, String descPath, String fileName) throws IOException {if( srcPath==null || srcPath.length()==0 ) {log.info("源文件路徑為空,請核實!");throw new IOException("源文件路徑為空,請核實!");}if( descPath==null || descPath.length()==0 ) {log.info("目標文件路徑為空,請核實!");throw new IOException("目標文件路徑為空,請核實!");}if( fileName==null || fileName.length()==0 ) {log.info("源文件名為空,請核實!");throw new IOException("源文件名為空,請核實!");}File descDir;File srcFile ;File descFile ;descDir = new File(descPath);if( !descDir.exists() ) {descDir.mkdirs();}srcFile = new File(srcPath,fileName);descFile = new File(descPath,fileName);if( descFile.exists() ) {descFile.delete();}srcFile.renameTo(descFile);}/*** 刪除指定文件* @param fileName 文件名稱* @return* @throws IOException*/public static void delFile(String fileName) throws IOException{if( fileName==null || fileName.length()==0 ) {log.info("需刪除文件的文件名為空,請核實!");throw new IOException("需刪除文件的文件名為空,請核實!");}File file = new File(fileName);if( file.exists() ) {file.delete();}}/*** 根據(jù)指定文件路徑、文件名、文件前綴生成文件名,并替換路徑分隔符未操作系統(tǒng)的分隔符* @param filePath 文件路徑,最后可以用"\\"或"/"作為結(jié)尾* @param fileName 文件名稱* @param prefix 需在文件名稱上添加的前綴** @return String 結(jié)果文件名*/public static String getFileName(String filePath, String fileName, String prefix)throws IOException {if( filePath==null || filePath.length()==0 ) {log.info("文件路徑為空,請核實!");throw new IOException("文件路徑為空,請核實!");}if( fileName==null || fileName.length()==0 ) {log.info("文件名稱為空,請核實!");throw new IOException("文件名稱為空,請核實!");}if( prefix==null ) {log.info("文件名前綴為空,請核實!");throw new IOException("文件名稱為空,請核實!");}String rtnFileName ;String separator ;separator = System.getProperty("file.separator");if( filePath.indexOf("\\")>=0 ) {rtnFileName = filePath.replace('\\', separator.toCharArray()[0]);}else if( filePath.indexOf("/")>=0 ) {rtnFileName = filePath.replace('/', separator.toCharArray()[0]);}else {rtnFileName = filePath;}if( !rtnFileName.endsWith(separator) ) {rtnFileName += separator;}if( prefix.length()!=0 ) {rtnFileName += prefix;}rtnFileName += fileName;return rtnFileName;}/*** 移動文件位置* @param* @return* @throws IOException*/public void seek(long pos) throws IOException {if( file!=null ) {file.seek(pos);}}/*** 移動文件位置* @param* @return* @throws IOException*/public long getFilePointer() throws IOException {if( file!=null ) {return file.getFilePointer();}else {throw new IOException("文件未打開.");}}/*** 根據(jù)緩沖區(qū)大小讀取適當?shù)奈募袛?shù),讀取的文件行數(shù)據(jù)保存在數(shù)組列表中* @param buffer 緩沖區(qū)* @param offset 數(shù)據(jù)存放在緩沖區(qū)中的偏移量* @param lineList 行輸出列表* @return int 下一批讀入數(shù)據(jù)存放的偏移量* @throws IOException*/public int readFileLines(byte[] buffer, int offset, List lineList) throws Exception {try {// 從文件中讀取一批數(shù)據(jù)int len = read(buffer, offset, buffer.length - offset);if( len==-1 && offset==0 ) {return 0;}// 確定文件的行分隔符String separator = null;if( indexOf(buffer, offset + len, 0, "\r\n".getBytes())!=-1 ) {separator = "\r\n";}else if( indexOf(buffer, offset + len, 0, "\n".getBytes())!=-1 ) {separator = "\n";}if( separator!=null ) {int index=0;while( index<len+offset ) {int next = indexOf(buffer, offset + len, index, separator.getBytes());if( next==-1 ) {break;}String line=new String(buffer, index, next - index);lineList.add(line);index = next + separator.length();}int offsetnew = offset + len - index;byte[] temp = new byte[offsetnew];System.arraycopy(buffer, index, temp, 0, offsetnew );System.arraycopy(temp, 0, buffer, 0, offsetnew);}else {String line;if( len==-1 ) {line = new String(buffer, 0, offset);}else {line = new String(buffer, 0, offset + len);}lineList.add(line);return 0;}return offset;} catch (Exception e) {throw e;}}/*** 將列表中的行數(shù)據(jù)寫入到文件中,寫入次數(shù)根據(jù)緩沖區(qū)大小自行調(diào)節(jié)* @param buffer 緩沖區(qū)* @param lineList 行數(shù)據(jù)列表* @throws IOException*/public void writeFileLines(byte[] buffer, List lineList) throws Exception {try {int offset=0;for( int index=0; index<lineList.size(); index++ ) {String line = (String)lineList.get(index) + "\n";byte[] temp = line.getBytes();if( offset + temp.length>buffer.length ) {write(buffer, 0, offset);offset = 0;}System.arraycopy(temp, 0, buffer, offset, temp.length );offset += temp.length;}if( offset>0 ) {file.write(buffer, 0, offset);}} catch (Exception e) {throw e;}}/*** 從長度尾length的數(shù)據(jù)緩沖區(qū)中index位置開始搜索指定的字符串* @param buffer 緩沖區(qū)* @param length 緩沖區(qū)數(shù)據(jù)大小* @param index 開始搜索位置* @param str 指定的搜索字符串* @return 指定的搜索字符串的位置,如果沒有搜索到返回-1*/public static int indexOf(byte[] buffer, int length, int index, byte[] str){boolean find=false;int tempIndex=index;if( tempIndex>=0 ){while(length-tempIndex>=str.length){int i;for( i=0; i<str.length; i++){if( buffer[tempIndex+i]!=str[i]){break;}}if( i==str.length ){find=true;break;}else{tempIndex++;}}}if( !find )tempIndex=-1;return tempIndex;}/*** 對指定文件壓縮,壓縮后文件名后添加".zip"* @param fileName 文件名* @throws Exception*/public static void zip(String fileName) throws Exception {File inFile = new File(fileName);File outFile = new File(fileName + ".zip");FileInputStream in =null;FileOutputStream out =null;ZipOutputStream zipOut=null;try {in = new FileInputStream(inFile);out = new FileOutputStream(outFile);zipOut = new ZipOutputStream(out);zipOut.putNextEntry(new ZipEntry(fileName));byte[] buffer = new byte[FILE_BUFFER_SIZE];while(true) {int len = in.read(buffer, 0, FILE_BUFFER_SIZE);if( len>0 ) {zipOut.write(buffer, 0, len);}else {break;}}zipOut.closeEntry();if( !inFile.delete() ) {log.info("文件" + fileName + "刪除失敗!");}} catch (IOException e) {log.error("",e);}finally{try {if (zipOut != null) {zipOut.close();}if (out != null) {out.close();}if (in != null) {in.close();}} catch (Exception e2) {log.error("",e2);}}}/*** 對指定文件進行解壓縮,注意:指定文件必須以".zip"結(jié)尾,但指定的文件名不含".zip"部分,解壓后文件去掉".zip"部分* @param fileName 文件名* @throws Exception*/public static void unzip(String fileName) throws Exception {File inFile = new File(fileName + ".zip");File outFile = new File(fileName);FileInputStream in =null;FileOutputStream out =null;ZipInputStream unzipIn=null;try {in = new FileInputStream(inFile);out = new FileOutputStream(outFile);unzipIn = new ZipInputStream(in);unzipIn.getNextEntry();byte[] buffer = new byte[FILE_BUFFER_SIZE];while(true) {int len = unzipIn.read(buffer, 0, FILE_BUFFER_SIZE);if( len>0 ) {out.write(buffer, 0, len);}else {break;}}unzipIn.closeEntry();if( !inFile.delete() ) {log.info("文件" + fileName + ".zip刪除失敗!");}} catch (IOException e) {log.error("",e);}finally{try {if (unzipIn != null) {unzipIn.close();}if (out != null) {out.close();}if (in != null) {in.close();}} catch (Exception e2) {log.error("",e2);}}}/*** 對指定文件進行壓縮,壓縮后文件名后添加".gz"* @param fileName 文件名* @throws Exception*/public static void gzip(String fileName) throws Exception {File inFile = new File(fileName);File outFile = new File(fileName + ".gz");FileInputStream in =null;FileOutputStream out =null;GZIPOutputStream gzipOut=null;try {in = new FileInputStream(inFile);out = new FileOutputStream(outFile);gzipOut = new GZIPOutputStream(out);byte[] buffer = new byte[FILE_BUFFER_SIZE];while(true) {int len = in.read(buffer, 0, FILE_BUFFER_SIZE);if( len>0 ) {gzipOut.write(buffer, 0, len);}else {break;}}if( !inFile.delete() ) {log.info("文件" + fileName + "刪除失敗!");}} catch (IOException e) {log.error("",e);}finally{try {if (gzipOut != null) {gzipOut.close();}if (out != null) {out.close();}if (in != null) {in.close();}} catch (Exception e2) {log.error("",e2);}}}/*** 對指定文件進行解壓縮,注意:指定文件必須以".gz"結(jié)尾,但指定的文件名不含".gz"部分,解壓后文件去掉".gz"部分* @param fileName 文件名* @throws Exception*/public static void gunzip(String fileName) throws Exception {File inFile = new File(fileName + ".gz");File outFile = new File(fileName);FileInputStream in =null;FileOutputStream out =null;GZIPInputStream gunzipIn=null;try {in = new FileInputStream(inFile);out = new FileOutputStream(outFile);gunzipIn = new GZIPInputStream(in);byte[] buffer = new byte[FILE_BUFFER_SIZE];while(true) {int len = gunzipIn.read(buffer, 0, FILE_BUFFER_SIZE);if( len>0 ) {out.write(buffer, 0, len);}else {break;}}if( !inFile.delete() ) {log.info("文件" + fileName + ".gz刪除失敗!");}} catch (IOException e) {log.error("",e);}finally{try {if (gunzipIn != null) {gunzipIn.close();}if (out != null) {out.close();}if (in != null) {in.close();}} catch (Exception e2) {log.error("",e2);}}}/*** zipfile 要解壓的文件* dir 解壓存放的文件夾*/public static void unzipToDir(File zipfile, File dir) throws Exception {// 解壓文件不存在時返回if (!zipfile.exists()) {return;}// 釋放目錄不存時創(chuàng)建if (!dir.exists()) {dir.mkdirs();}// 釋放目錄不為目錄時返回if (!dir.isDirectory()) {return;}FileInputStream fin = null;try {fin = new FileInputStream(zipfile);ZipInputStream zin = new ZipInputStream(fin);java.util.zip.ZipEntry entry = null;while ((entry = zin.getNextEntry()) != null) {File tmp = new File(dir, entry.getName());if (entry.isDirectory()) {tmp.mkdirs();} else {byte[] buff = new byte[4096];int len = 0;tmp.getParentFile().mkdirs();FileOutputStream fout = new FileOutputStream(tmp);while ((len = zin.read(buff)) != -1) {fout.write(buff, 0, len);}zin.closeEntry();fout.close();}}} catch (Exception e) {throw new Exception(Exception.SYS_ERR, e.getMessage(), e);}finally{if(fin!=null){try {fin.close();} catch (IOException e) {log.error("",e);}}}}public static boolean saveFile(InputStream is, String fileName){boolean flag = false;try {// 創(chuàng)建臨時文件,用于解壓File file = new File(fileName);FileOutputStream os = new FileOutputStream(file);try {byte[] bytes = new byte[2048];int read;while ((read = is.read(bytes)) != -1) {os.write(bytes, 0, read);}} finally {os.close();}flag=true;} catch (Exception e) {log.error("saveFile",e);flag = false;}return flag;}/*** 解壓tar.gz 文件 * @param filename 要解壓的tar.gz文件對象* @param outputDir 要解壓到某個指定的目錄下 * @throws Exception*/public static void unTarGz(String filename,String outputDir) throws Exception{unTarGz(filename, outputDir, -1);}/*** 解壓tar.gz * @param filename 要解壓的tar.gz文件對象* @param outputDir 要解壓到某個指定的目錄下 * @param fileNumMax 文件 tar文件的限制個數(shù)* @throws Exception*/public static void unTarGz(String filename,String outputDir,int fileNumMax) throws Exception{TarInputStream tarIn = null;FileInputStream fileIn = null;try{File file=new File(filename);fileIn= new FileInputStream(file);tarIn = new TarInputStream(new GZIPInputStream(new BufferedInputStream(fileIn)),1024 * 2);createDirectory(outputDir,null);//創(chuàng)建輸出目錄 TarEntry entry = null;//根據(jù)tar包內(nèi)文件數(shù)目 限制 循環(huán)次數(shù) ,防止死循環(huán)int i=0;while( (entry = tarIn.getNextEntry()) != null ){if (fileNumMax > 0) {if (i > fileNumMax) {log.error("fileNumMax=" + fileNumMax + ",當前次數(shù)是:" + i+",超過了tar文件的限制個數(shù)");throw new Exception("解壓歸檔文件出現(xiàn)異常,超過了tar文件的限制個數(shù)");}i = i + 1;}if(entry.isDirectory()){//是目錄entry.getName();createDirectory(outputDir,entry.getName());//創(chuàng)建空目錄 }else{//是文件File tmpFile = new File(outputDir + "/" + entry.getName());createDirectory(tmpFile.getParent() + "/",null);//創(chuàng)建輸出目錄 //FileOutputStream out = null; try{FileOutputStream out = new FileOutputStream(tmpFile);int length = 0;byte[] b = new byte[2048];while((length = tarIn.read(b)) != -1){out.write(b, 0, length);}if (out != null)out.close();}catch(IOException ex){log.error(ex.getMessage(),ex);throw new Exception("解壓歸檔文件出現(xiàn)異常,寫文件異常");} // finally { // if (out != null) // out.close(); // } }}}catch(Exception ex){log.error("解壓歸檔文件出現(xiàn)異常",ex);throw new Exception("解壓歸檔文件出現(xiàn)異常",ex);} finally{try{if(tarIn != null){tarIn.close();}if(fileIn != null){fileIn.close();}}catch(Exception ex){log.error("******關(guān)閉流ERROR******",ex);}}}/*** 構(gòu)建目錄 * @param outputDir* @param subDir*/public static void createDirectory(String outputDir,String subDir){File file = new File(outputDir);if(!(subDir == null || "".equals(subDir.trim()))){//子目錄不為空 file = new File(outputDir + "/" + subDir);}if(!file.exists()){if(!file.getParentFile().exists())file.getParentFile().mkdirs();file.mkdirs();}}}總結(jié)
以上是生活随笔為你收集整理的文件操作工具类FileUtil的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java程序中date类型比较大小总结
- 下一篇: java操作字符串的工具类StringU