读取一个文本文档,例如有1~10行,要求按10~1行的顺序输出.并保存予原文件

 Java代码

package test49;

//package com.color.io;

/*
 * Main.java
 *
 * Created on 2000年9月29日, 下午5:17
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
 *
 * @author admin
 */
public class Main {

    /** Creates a new instance of Main */
    public Main() {
    }

    /**
     * @param args
     *            the command line arguments
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        // 按文件大小来产生构建buffer
        char[] buffer = new char[(int) new File("D://新建 文本文档.txt").length()];
        Reader reader = null;
        try {
            reader = new FileReader("D://新建 文本文档.txt");

            int offset;
            while ((offset = reader.read(buffer)) > 0)
                System.out.print(new String(buffer, 0, offset));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                }
        }
        // 将整个文件读入,然后构造成一个String
        String s = new String(buffer);
        // 将这个String按换行符拆分成String数组
        String[] reverse = s.split("/r/n");
        // 构造文件,原来那个文件
        File file = new File("D://新建 文本文档.txt");
        Writer writer = new FileWriter(file);
        for (int i = reverse.length - 1; i >= 0; i--) {
            // 反转写入
            writer.write(reverse[i] + "/r/n");
        }
        writer.close();
    }

}

 

或者
Java代码

package test49;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

public class TxtReverse {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        FileReader fr = new FileReader(new File("d://a.txt"));
        BufferedReader br = new BufferedReader(fr);
        ArrayList<String> al = new ArrayList<String>();
        String line;
        while ((line = br.readLine()) != null) {
            al.add(line);
        }

        for (int i = al.size() - 1; i >= 0; i--) {
            System.out.println(al.get(i));
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值