文件操作工具类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();
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leo825...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值