Java 工具集 | 文本文件的读写

自己设计一个 SimpleFileUtil 处理文本文件

这里将会介绍一个我自己写的,而且是经常使用到的一个处理文本文件的工具集合。该工具主要是封装文件的读取,以及提供一些方便的方法进行对读取的文件进行特殊处理,同时也提供方法将一些对象数据输出到文本文件中。

主要的功能类

package cn.donespeak.tools.util.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class SimpleFileUtil {
	/**
	 * 移除本地非目录文件
	 * @param filePath
	 * @return  <code>true</code> 移除成功,
	 * 			<code>false</code> 移除失败
	 */
	public static boolean removeLocalFile(String filePath){
		File f = new File(filePath);
		if(f.exists()){
			if(f.isDirectory()){
				return false;
			}
			f.delete();
		}
		return !f.exists();
	}
	
	/**
	 * 移除一个目录内所有文件,同时可以指定是否移除目录自身
	 * @param dirPath
	 * @param removeItself 是否移除目录自身
	 * @return 如果removeItself为true, 结果为指定目录是否已被存在,否则表示指定目录内的所有文件是否已经被成功删除
	 */
	public static boolean removeDirectory(String dirPath, boolean removeItself){
		File dir = new File(dirPath);
		if(!dir.exists()){
			return true;
		}
		if(!dir.isDirectory()){
			return false;
		}
		File[] files = dir.listFiles();
		for(File f: files){
			if(f.isDirectory()){
				removeDirectory(f.getAbsolutePath(), true);
			} else {
				f.delete();
			}			
		}
		if(removeItself){
			dir.delete();
			return !dir.exists();
		} else {
			files = dir.listFiles();
			return files.length == 0;
		}
	}
	
	/**
	 * 清空目录内的所有文件
	 * @param dirPath
	 * @return
	 */
	public static boolean emptyDirectory(String dirPath){
		return removeDirectory(dirPath, false);
		
	}
	
	/**
	 * 将文件路径分隔符替换成系统对应的文件路径分隔符
	 * @param filePath
	 * @return
	 */
	public static String normalizeFileSeparator(String filePath){
		if(filePath == null){
			return null;
		}
		char targetSeparor = File.separator.charAt(0);
		char oldSeparator = '\\';
		System.out.println();
		System.out.println(targetSeparor == oldSeparator);
		if(targetSeparor == oldSeparator){
			oldSeparator = '/';
		}
		return filePath.trim().replace(oldSeparator, targetSeparor);
	}
	
	/**
	 * 将文件的内容提取为一个字符串
	 * @param filePath
	 * @return
	 */
	public static String extractAsOneString(String filePath){
		BufferedReader reader = null;
		StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            String line = null;
            while((line = reader.readLine()) != null){
            	sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(reader != null){
                try {
                	reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        }
        return sb.toString();
	}
	
	/**
	 * 将文件中的内容按照提取每行一个字符的方式到一个字符串列表
	 * @param filePath
	 * @return
	 * @throws IOException 
	 */
	public static List<String> extractAsOneList(String filePath) throws IOException{
		return extractAsOneList(filePath, new StringObjectifier<String>(){
			@Override
			public String objectify(int index, String line) {
				return line;
			}
		});
	}
	
	/**
	 * 提取文件内容中的每一个行文本,并利用formater格式化为一个特殊对象
	 * @param filePath
	 * @param formater
	 * @return
	 * @throws IOException
	 */
	public static <T> List<T> extractAsOneList(String filePath, StringObjectifier<T> formater) throws IOException{
		BufferedReader reader = null;
		List<T> list = new ArrayList<T>();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            String line = null;
            int index = 0;
            while((line = reader.readLine()) != null){
            	T t = formater.objectify(index ++, line);
            	if(t != null){
            		list.add(t);
            	}
            }
        } finally {
        	if(reader != null) {
	        	try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
        return list;
	}

	/**
	 * 将字符串集合按照每个元素一行的方式输出到一个文件中
	 * @param collection
	 * @param destFilePath
	 * @param append 是否在原来的文件中拓展
	 * @throws IOException
	 */
	public static void toFile(Collection<String> collection, String destFilePath, boolean append) throws IOException {
		toFile(collection, destFilePath, append, new ObjectStringifier<String>(){
			@Override
			public String stringify(String t) {
				return t;
			}
		});
	}
	
	/**
	 * 将对象集合按照每个元素一行的方式输出到一个文件中,
	 * 	可以通过objectStringifier格式化每个对象为一个字符串
	 * @param collection
	 * @param destFilePath
	 * @param append 是否在原来的文件中拓展
	 * @param objectStringifier 定义对象格式化为字符串的方式
	 * @throws IOException
	 */
	public static <T> void toFile(Collection<T> collection, String destFilePath, boolean append,
			ObjectStringifier<T> objectStringifier) throws IOException{
		
		BufferedWriter writer = null;
        try {
        	writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFilePath, append)));
            
            for(T t: collection){
            	String line = objectStringifier.stringify(t);
            	writer.write(line);
            	writer.newLine();
            }
        	writer.flush();
        } finally {
            if(writer != null){
                try {
                	writer.close();
                	writer = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        }
	}
	
	/**
	 * 拷贝文件
	 * @param srcFile
	 * @param destFile
	 * @return
	 */
	public static boolean copyFileTo(File srcFile, File destFile){
		if(srcFile == null || !srcFile.exists() || destFile == null){
			return false;
		}
		if(srcFile.getAbsolutePath().equals(destFile.getAbsolutePath())){
			return true;
		}
		try {
			if(destFile.exists()){
				destFile.delete();
			}
			Files.copy(srcFile.toPath(), destFile.toPath());
		} catch (IOException e) {
			return false;
		}
		return true;
	}
	
	public static String getExtension(File file) {
		return getExtension(file.getName());
	}
	
	public static String getExtension(String filePath) {
    	int lastPoint = filePath.lastIndexOf(".");
    	return lastPoint < 0? "": filePath.substring(lastPoint + 1);
	}
}

将字符串格式化为对象的接口

package cn.donespeak.tools.util.file;

public interface StringObjectifier <T>{
	T objectify(int index, String line);
}

将对象格式化为字符串的接口

package cn.donespeak.tools.util.file;

public interface ObjectStringifier<T> {
	String stringify(T t);
}

org.apache.commons.io.FileUtils

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READme.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值