日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

文件操作工具类FileUtil

發布時間:2025/3/19 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 文件操作工具类FileUtil 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

分享一個文件處理的工具類,依賴如下:

<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;}/*** 設置文件操作公用類中的文件名稱、文件打開模式參數* @param fileName 文件名稱* @param mode 文件打開模式* @return*/public void setFileInfo(String fileName, String mode) {this.fileName = fileName;this.mode = mode;}/*** 設置文件操作公用類中的文件名稱參數* @param fileName 文件名稱* @return*/public void setFileName(String fileName) {this.fileName = fileName;}/*** 設置文件操作公用類中的文件名稱* @return String 文件名稱*/public String getFileName() {return this.fileName;}/*** 設置文件操作公用類中的文件打開模式參數* @param mode 文件打開模式* @return*/public void setMode(String mode) {this.mode = mode;}/*** 獲取文件操作公用類中的文件打開模式參數* @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();}/*** 通過已賦值參數,打開相應文件* @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 文件行數據* @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 文件行數據* @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());}}/*** 數據刷新* @param* @return* @throws IOException*/public void flush() throws IOException {if( file!=null ) {FileChannel fd = file.getChannel();fd.force(true);}}/*** 關閉已打開文件* @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();}}/*** 根據指定文件路徑、文件名、文件前綴生成文件名,并替換路徑分隔符未操作系統的分隔符* @param filePath 文件路徑,最后可以用"\\"或"/"作為結尾* @param fileName 文件名稱* @param prefix 需在文件名稱上添加的前綴** @return String 結果文件名*/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("文件未打開.");}}/*** 根據緩沖區大小讀取適當的文件行數,讀取的文件行數據保存在數組列表中* @param buffer 緩沖區* @param offset 數據存放在緩沖區中的偏移量* @param lineList 行輸出列表* @return int 下一批讀入數據存放的偏移量* @throws IOException*/public int readFileLines(byte[] buffer, int offset, List lineList) throws Exception {try {// 從文件中讀取一批數據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;}}/*** 將列表中的行數據寫入到文件中,寫入次數根據緩沖區大小自行調節* @param buffer 緩沖區* @param lineList 行數據列表* @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的數據緩沖區中index位置開始搜索指定的字符串* @param buffer 緩沖區* @param length 緩沖區數據大小* @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"結尾,但指定的文件名不含".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"結尾,但指定的文件名不含".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;}// 釋放目錄不存時創建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 {// 創建臨時文件,用于解壓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文件的限制個數* @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);//創建輸出目錄 TarEntry entry = null;//根據tar包內文件數目 限制 循環次數 ,防止死循環int i=0;while( (entry = tarIn.getNextEntry()) != null ){if (fileNumMax > 0) {if (i > fileNumMax) {log.error("fileNumMax=" + fileNumMax + ",當前次數是:" + i+",超過了tar文件的限制個數");throw new Exception("解壓歸檔文件出現異常,超過了tar文件的限制個數");}i = i + 1;}if(entry.isDirectory()){//是目錄entry.getName();createDirectory(outputDir,entry.getName());//創建空目錄 }else{//是文件File tmpFile = new File(outputDir + "/" + entry.getName());createDirectory(tmpFile.getParent() + "/",null);//創建輸出目錄 //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("解壓歸檔文件出現異常,寫文件異常");} // finally { // if (out != null) // out.close(); // } }}}catch(Exception ex){log.error("解壓歸檔文件出現異常",ex);throw new Exception("解壓歸檔文件出現異常",ex);} finally{try{if(tarIn != null){tarIn.close();}if(fileIn != null){fileIn.close();}}catch(Exception ex){log.error("******關閉流ERROR******",ex);}}}/*** 構建目錄 * @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();}}}

總結

以上是生活随笔為你收集整理的文件操作工具类FileUtil的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 黄色国产视频网站 | 亚洲免费av电影 | www.天天操 | 亚洲视频 一区 | 日本 在线| av黄页| 午夜黄视频 | 五月天婷婷在线观看 | 亚洲免费黄色网 | 成人tv| 亚洲女人18毛片水真多 | av免费在线网站 | 一区二区小视频 | 九色蝌蚪porny | 久啪视频| 不卡的毛片| 国产第一精品 | 日韩免费高清 | 一区二区三区伦理片 | 亚洲一区二区三区91 | 俄罗斯av片 | 四川丰满少妇被弄到高潮 | 91最新视频 | 国产成人精品久久二区二区 | 中国美女乱淫免费看视频 | 久久影院视频 | 精品人妻一区二区三区浪潮在线 | 曰批免费视频播放免费 | 国产51精品 | 欧美性色黄大片手机版 | 亚洲国产精品一区二区久久hs | 国产美女又黄又爽又色视频免费 | 在线三级av | 日本激情在线 | 18欧美性xxxx极品hd | 人妻熟女一区二区aⅴ水野 91在线观看视频 | 国内自拍av | 在线观看日本一区 | 狠狠干2018| 日本欧美三级 | 久久亚洲AV成人无码一二三 | 久久精品aaaaaa毛片 | 网爆门在线 | 精品国产一区在线观看 | 欧美一区欧美二区 | 日韩熟女精品一区二区三区 | 五月天中文字幕 | 又黄又刺激的视频 | 最新激情网站 | 伊人色婷婷 | 四虎黄色网址 | 双性懵懂美人被强制调教 | 五月天亚洲色图 | 欧美在线一区二区 | 无码人妻一区二区三区在线视频 | 久热最新视频 | 538在线精品 | 风流老熟女一区二区三区 | 一区二区天堂 | 一区二区日韩视频 | 四虎精品一区二区 | 欧美亚洲丝袜 | 99久久亚洲精品日本无码 | 999av视频| 亚洲色精品三区二区一区 | 欧美乱妇日本无乱码特黄大片 | 久夜精品 | 亚洲一区二区国产 | 好吊色视频一区二区三区 | 国产一级啪啪 | 少妇2做爰bd在线意大利堕落 | 成人国产精品免费观看视频 | 无套内谢的新婚少妇国语播放 | 天天操天天草 | 亚洲国产日韩欧美 | 日韩精品在线观看AV | 91精品人妻一区二区三区 | 国产一区亚洲 | 污视频网站在线播放 | a毛片基地 | 国产精品久久久久久精 | 国产精品va在线观看无码 | 色播99| 激情第一页 | 人人射| 777精品伊人久久久久大香线蕉 | 嫩草嫩草嫩草嫩草嫩草 | 岛国av片 | 欧美人伦| 黄色视屏免费 | 国产美女网站视频 | 国产视频精品视频 | 成人免费视频观看视频 | 国产免费啪啪 | 日韩av不卡在线观看 | 欧美一级夜夜爽 | 免费毛片基地 | 熊猫成人网 | 成人动漫在线观看 |