Java I/O学习 文件读写工具

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.ObjectInputStream.GetField;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;


class TextFile extends ArrayList<String> {
	
	public TextFile(String filename, String splitter) {
		super(Arrays.asList(read(filename).split(splitter)));
	}
	
	//通过文件路径读取一行一行的读取文件信息
	public static String read(String filename){
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(new File(filename).getAbsolutePath()));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String s;
		try {
			while ((s = br.readLine()) != null) {
				sb.append(s); sb.append("\n");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				br.close(); //记得要关闭文件
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	//通过文件名,以及要写入的内容,一追加的方式写入文件
	public static void write(String filename, String text) throws IOException {
		PrintWriter pw = null;
		try {
			//设置为追加的方式
			pw = new PrintWriter(new FileWriter(filename, true));
			pw.println(text);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			pw.close(); //关闭
		}		
	}
	//这个写入是根据构造函数,构造之后读取了信息,然后写入指定文件
	public void write(String filename) {
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new FileWriter(filename, true));
			for (String item : this) {
				pw.println(item);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			pw.close();
		}
	}
	
}
public class Test{

	public static void main(String[] args) throws IOException {
		TextFile.write("/home/estar/Test/a.java", "加油,你行");
		System.out.println(TextFile.read("/home/estar/Test/a.java"));
		
		TextFile textFile = new TextFile("/home/estar/Test/a.java", "\n");
		textFile.write("/home/estar/Test/b.java");
		System.out.println(TextFile.read("/home/estar/Test/b.java"));
	}
}

  

 

posted @ 2013-11-26 14:36  E_star  阅读(288)  评论(0编辑  收藏  举报