18.7 文件读写的使用工具

下边展示了一个读写文件的工具类, 通过继承arrayList将文件逐行读入内存并保存的实现也值得借鉴, 当然, 在实际使用中还要考虑性能和实用性.

package com.cnsuning.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

public class TextFile extends ArrayList<String> {
	public TextFile(String fileName){
		this(fileName,"\n");
		//split分割经常会产生空白, 尝试删除
		if(get(0).equals("")){
			remove(0);
		}
		
	}

	public TextFile(String fileName, String split) {
		super(Arrays.asList(read(fileName).split(split)));
	}

	public static String read(String fileName) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(fileName));
			try {
				String line;
				while (null != (line = reader.readLine())) {
					sb.append(line);
					sb.append("\n");
				}
			} finally {
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static void write(String fileName, String text) {
		try {
			PrintWriter writer = new PrintWriter(new BufferedWriter(
					new FileWriter(fileName)));
			try {
				writer.print(text);
			} finally {
				writer.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void write(String fileName){
		try {
			PrintWriter writer = new PrintWriter(fileName);
			for(String line: this){
				writer.println(line);
			}
			writer.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public static void main(String[] args) {
		TextFile text = new TextFile("D:\\work\\会员账户管理\\sales_svn.txt");
		StringBuilder sb = new StringBuilder();
		int lineNum = 1;
		for(String line: text){
			sb.append(lineNum);
			sb.append(": ");
			sb.append(line);
			sb.append("\n");
			lineNum++;
		}
		TextFile.write("D:\\test.txt", sb.toString());
		System.out.println(TextFile.read("D:\\work\\会员账户管理\\sales_svn.txt"));
		System.out.println(TextFile.read("D:\\test.txt"));
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值