File文件操作工具类

51 篇文章 0 订阅
17 篇文章 0 订阅
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * <p>
 * Title: 文件读写类
 * </p>
 * <p>
 * Description: 文件读写类
 * </p>
 */
public class FileUtil {
	private static Logger log = Logger.getLogger(FileUtil.class);

	/**
	 * 读取所有的文件数据
	 * 
	 * @param filePath
	 */
	public static String readFileAll(String filePath) {
		String resultString = "";
		FileReader fr = null;
		try {
			fr = new FileReader(filePath);
			// 关键在于读取过程中,要判断所读取的字符是否已经到了文件的末尾,并且这个字符是不是文件中的断行符,即判断该字符值是否为13。
			int c = fr.read();// 从文件中读取一个字符
			// 判断是否已读到文件结尾
			while (c != -1) {
				resultString += ((char) c);// 输出读到的数据
				c = fr.read();// 从文件中继续读取数据
				if (c == 13) {// 判断是否为断行字符
					fr.skip(1);// 略过一个字符
				    c=fr.read();//读取一个字符
				    System.out.println(resultString);
				}
			}
		} catch (Exception e) {
			log.error("", e);
		} finally {
			if (fr != null) {
				try {
					fr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.error("", e);
				}
			}
		}
		return resultString;
	}

	/**
	 * 一行一行读取数据
	 * 
	 * @param filePath
	 */
	public static String readFileLine(String filePath) {
		String resultString = "";
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(filePath);// 建立FileReader对象,并实例化为fr
			br = new BufferedReader(fr);// 建立BufferedReader对象,并实例化为br
			String Line = br.readLine();// 从文件读取一行字符串
			// 判断读取到的字符串是否不为空
			while (Line != null) {
				resultString += Line + "\r\n";// 输出从文件中读取的数据
				Line = br.readLine();// 从文件中继续读取一行数据
			}

		} catch (Exception e) {
			log.error("", e);
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (fr != null) {
					fr.close();// 关闭文件
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("", e);
			}

		}
		return resultString;
	}

	/**
	 * 写数据到文件
	 * 
	 * @param filePath
	 */
	public static void writeFileAll(String fileBody, String filepath) {
		FileWriter fw = null;
		try {
			fw = new FileWriter(filepath);
			// 将字符串写入文件
			fw.write(fileBody);
		} catch (Exception e) {
			log.error("", e);
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.error("", e);
				}
			}
		}
	}

	/**
	 * 逐行写数据到文件
	 * 
	 * @param filePath
	 */
	public void writeFileLine(String filepath) {
		try {
			FileWriter fw = new FileWriter(filepath);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write("大家好!");
			bw.write("本书是《JSP编程技巧》。");
			bw.newLine();// 断行
			bw.write("请多多指教!");
			bw.flush();// 将数据更新至文件
			fw.close();// 关闭文件流
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 追加写数据到文件
	 * 
	 * @param filePath
	 */
	public void writeFileAppend(String fileBody, String filepath) {
		try {

			RandomAccessFile rf = new RandomAccessFile(filepath, "rw");// 定义一个类RandomAccessFile的对象,并实例化
			rf.seek(rf.length());// 将指针移动到文件末尾
			rf.writeBytes(fileBody);
			rf.close();// 关闭文件流
			System.out.println("写入文件内容为:<br>");
			FileReader fr = new FileReader(filepath);
			BufferedReader br = new BufferedReader(fr);// 读取文件的BufferedRead对象
			String Line = br.readLine();
			while (Line != null) {
				System.out.println(Line + "<br>");
				Line = br.readLine();
			}
			fr.close();// 关闭文件

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取目录下的所有文件名
	 * 
	 * @param filePath
	 * @return 所有文件名
	 */
	public static List readFile(String filePath) {
		List<String> fileNameList = new ArrayList<String>();
		try {
			File file = new File(filePath);
			if (!file.isDirectory()) {
				fileNameList.add(file.getName());
			} else if (file.isDirectory()) {
				String[] readList = file.list();
				for (String i : readList) {
					File readFile = new File(filePath + "\\" + i);
					if (!readFile.isDirectory()) {
						fileNameList.add(readFile.getName());
					} else if (readFile.isDirectory()) {
						fileNameList.add(filePath + "\\" + i);
					}
				}
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return fileNameList;
	}
	
	
	
	/**
	 * 日对账获取目录下的文件名
	 * 
	 * @param filePath
	 * @return 所有文件名
	 */
	public static List getDayFileName(String filePath){
		List<String> fileNameList = new ArrayList<String>();
		try {
			File file = new File(filePath);
			if (!file.isDirectory()) {
				fileNameList.add(file.getName());
			} else if (file.isDirectory()) {
				String[] readList = file.list();
				for (String i : readList) {
					fileNameList.add(i);
				}
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return fileNameList;
	}
	public static List readFileB(String filePath) {
		List<String> fileNameList = new ArrayList<String>();
		try {
			File file = new File(filePath);
			if (!file.isDirectory()) {
				fileNameList.add(file.getName());
			} else if (file.isDirectory()) {
				String[] readList = file.list();
				for (String i : readList) {
					File readFile = new File(filePath + "\\" + i);
					if (!readFile.isDirectory()) {
						fileNameList.add(readFile.getName());
					}
				}
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return fileNameList;
	}

	/**
	 * 将单个文件复制
	 * 
	 * @param oldPath
	 * @param newPath
	 */
	public static void copyFile(String oldPath, String newPath) {
		InputStream inStream = null;
		FileOutputStream fs = null;
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				inStream = new FileInputStream(oldPath); // 读入原文件
				fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					//System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}

			}
		} catch (Exception e) {
			log.error("", e);
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
				if (fs != null) {
					fs.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("", e);
			}
		}
	}
	
	/**
	 * 将单个文件复制
	 * 
	 * @param oldPath
	 * @param newPath
	 */
	public static void copyFile(File oldfile, File newfile) {
		InputStream inStream = null;
		FileOutputStream fs = null;
		try {
			int bytesum = 0;
			int byteread = 0;
			if (oldfile.exists()) { // 文件存在时
				inStream = new FileInputStream(oldfile); // 读入原文件
				fs = new FileOutputStream(newfile);
				byte[] buffer = new byte[1024];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}

			}
		} catch (Exception e) {
			log.error("", e);
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
				if (fs != null) {
					fs.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("", e);
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *            String 文件路径及名称 如c:/fqf.txt
	 * @param fileContent
	 *            String
	 * @return
	 */
	public static void deleteFile(String filePathAndName) {
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			java.io.File myDelFile = new java.io.File(filePath);
			if (myDelFile != null && myDelFile.exists()) {
				myDelFile.delete();
			}

		} catch (Exception e) {
			log.error("", e);
		}

	}
	 /**
     * 新建文件
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @return
     */
    public static String createFile(String filePathAndName ) {
     
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
            return filePath;
        }
        catch (Exception e) {
           
        }
		return null;
    }
    
	public static void main(String args[]) {
		FileUtil fileutil = new FileUtil();
		// System.out.print(fileutil.readFileLine("c://JZX2010112400010-se-1.txt"));
		// System.out.print(fileutil.writeFileAll("SHHB201252|2|4|1|1|\r\n010B2263E008PHM|CYX102|02|2|\r\n010B2263E008PI1|CYX102|02|2|\r\n","c://se.txt");
		// fileutil.writeFileAppend("append String!", "c://se.txt");
		// fileutil.copyFile("c://se.txt", "C://aa.txt");
		String str = fileutil.readFileLine("c://JZX2010112400010-se-1.txt");
		String[] arrstr = str.split("\r\n");
		for (String aaa : arrstr) {
			System.out.print(aaa);
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值