java实现操作文件的方法汇总实现

本文介绍了一个实用的Java文件操作工具类,包括文件的MD5校验、字节数组转换为文件、读取文件为字节数组、文件重命名、获取文件列表、创建目录、删除文件、解压文件并查找.bcp文件、复制文件等功能。通过这个工具类,开发者可以更方便地进行文件的相关操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码:
package lm;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;


import java.io.*;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;


public class FileUtil {

	static Logger LOG = LogManager.getLogger(FileUtil.class);

	static int rnCount=0;
	public static String getMD5(File file){
		String value = null;
		FileInputStream in = null;
		try{
			in = new FileInputStream(file);
			MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if (in != null){
				try{
					in.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
		}
		return value;
	}
	
	public static void byte2file(byte[] bs, String filename) {
		if(!(new File(filename).exists()))
			try {
				new File(filename).createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		FileOutputStream fos  = null;
		try {
			fos = new FileOutputStream(filename);
			fos.write(bs);			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(null!=fos)
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	public static byte[] fileToBytes(String filePath){
		File file = new File(filePath);
		byte[] ret = null;
		try {
			FileInputStream in = new FileInputStream(file);
			ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
			byte[] b = new byte[4096];
			int n;
			while ((n = in.read(b)) != -1){
				out.write(b, 0, n);
			}
			in.close();
			out.close();
			ret = out.toByteArray();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
	/**
	 * 把文件重新命名
	 * @param oldName	旧的文件路径
	 * @param newName	新的文件路径
	 * @return
	 */
	public static boolean moveFile(String oldName, String newName){
		File oldFile = new File(oldName);
		File newFile = new File(newName);
		try{
			if(newFile.getAbsolutePath().contains("load_error") && oldFile.getName().equalsIgnoreCase(newFile.getName())){
				newFile = new File(newName+"."+System.currentTimeMillis());
			}
			if(oldFile.renameTo(newFile)){
				LOG.info("remove file " + oldFile.getAbsolutePath() + " to " + newFile.getAbsolutePath() + " ok");
			}else{
				LOG.info("remove file " + oldFile.getAbsolutePath() + " to " + newFile.getAbsolutePath() + " ok");
				FileUtils.moveFile(oldFile, newFile);
			}
		
			//Thread.sleep(50);
		}catch(Exception e){			
			LOG.error(String.format("err file move %s to %s", oldFile.getAbsolutePath(), newFile.getAbsolutePath()));
			
			if(oldFile.delete()){
				LOG.info(String.format("remove err file %s ok",oldFile.getAbsolutePath()));
			}else{
				LOG.info(String.format("remove err file %s err",oldFile.getAbsolutePath()));
			}
			return false;
		}
		return true;
	}
	

	public static String[] getFileList(String filePath) {
		File file = new File(filePath);	
		return file.list();
	}
	
	public static void createDir(String filePath){
		File dir = new File(filePath);
		if (!dir.exists()){
			dir.mkdir();
		}
	}
	
	public static void deleteFile(String filePath){
		File file = new File(filePath);
		if (file.exists()){
			if (file.isDirectory()){
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++){
					files[i].delete();
				}
			}
			
			if(!(file.delete())){
				LOG.error(String.format("delete file %s error",file.getAbsolutePath()));				
			}else{
				LOG.debug(String.format("delete file %s ok",file.getAbsolutePath()));				
			}
			
		}
	}
	

	@SuppressWarnings("resource")
	public static String unZipFile(String fileName, String destDir) throws IOException{	
		String bcpFile = null;
		int len = 0;
		byte[] b = new byte[1024 * 2];
		File file = new File(fileName);
		ZipFile zipFile = new ZipFile(file);	
		if (fileName.endsWith(".zip")){
			ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
			ZipEntry entry = null;
			while((entry = zis.getNextEntry()) != null){
				if (entry.getName().endsWith(".bcp")){
					bcpFile = entry.getName();
				}
				
				String destFile = null;
				if (destDir.endsWith(File.separator)){
					destFile = destDir + entry.getName();
				}else{
					destFile = destDir + File.separator + entry.getName();
				}
				OutputStream os = new FileOutputStream(destFile);
				InputStream is = zipFile.getInputStream(entry);
				while ((len = is.read(b)) != -1){
					os.write(b, 0, len);
				}
				is.close();
				os.close();
			}
		}
		
		return bcpFile;
	}
	
	public static void main(String[] args){
		try {
			unZipFile("D:\\116_LOG_0.370000_4DD24EAE_05070.zip", "D:\\data");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void copyFile(String oldFile, String newFile) {
		
		File oldfile = new File(oldFile);
		File newfile = new File(newFile);
		if(oldfile.exists()){
			try {
				LOG.info(String.format("copy file %s to %s start",oldfile.getAbsolutePath(),newfile.getAbsolutePath()));
				FileUtils.copyFile(oldfile, newfile);
				LOG.info(String.format("copy file %s to %s ok",oldfile.getAbsolutePath(),newfile.getAbsolutePath()));
			} catch (IOException e) {
				LOG.error("copyt error:", e);
				LOG.error(String.format("copy file %s to %s err",oldfile.getAbsolutePath(),newfile.getAbsolutePath()));
			}
		}

	}
}
		
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值