JAVA IO 简单读写文件

/**
 *  简单读写文件类,有两个静态的读写方法
 */
public class TextFile extends ArrayList<String> {
    /*
     * 功能:将指定文件读出转换为字符串
     */
    public static String read(String fileName) {
        StringBuilder sb = new StringBuilder();
        try {
            // 读取字符文件
            BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
            // 为什么单独在这里加上try块而不是直接使用外边的try块?
            // 需要考虑这么一种情况,如果文件没有成功打开,则finally关闭文件会出问题
            try {
                String s;
                while ((s = in.readLine()) != null) {
                    sb.append(s + "\n");
                }
            }finally{
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     *
     * @param fileName 将要写入的文件名
     * @param text 写入的文本
     */
    public static void write(String fileName, String text){
        try{
            PrintWriter p = new PrintWriter(new File(fileName));
            try{
                p.print(text);
            }finally {
                p.close();
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    public TextFile(String fileName, String splitter){
        // 将文件内容按指定形式分割后存放在ArrayList中
        super(Arrays.asList(read(fileName).split(splitter)));
        if(get(0).equals("")) remove(0);
    }
    // 默认按行分割
    public TextFile(String fileName){
        this(fileName, "\n");
    }

    /** 将本对象保存数据写入文件中
     *
     * @param fileName 文件名
     */
    public void write(String fileName){
        try (
            PrintWriter out = new PrintWriter(new File(fileName))) {
            try{
                for(String item : this){
                    out.println(item);
                }
            }finally{
                out.close();
            }
        }catch(IOException e){
            throw new RuntimeException(e);
        }
    }
    // 测试
    public static void main(String[] args){
//        TextFile tf = new TextFile();
        String str = read("./src/com/lrx/IO/TextFile.java");
        write("test.txt", str);
        TextFile tf = new TextFile("test.txt");
        tf.write("test2.txt");
        TreeSet<String> t = new TreeSet<String>(new TextFile("test2.txt","\\W+"));

        System.out.println(t.headSet("a"));
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值