如何在Java中从头到尾(以相反的顺序)读取文件? [英] How to read file from end to start (in reverse order) in Java?

查看:65
本文介绍了如何在Java中从头到尾(以相反的顺序)读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件的结尾到开头以相反的方向读取文件,

I want to read file in opposite direction from end to the start my file,

[1322110800] LOG ROTATION: DAILY
[1322110800] LOG VERSION: 2.0
[1322110800] CURRENT HOST STATE:arsalan.hussain;DOWN;HARD;1;CRITICAL - Host Unreachable (192.168.1.107)
[1322110800] CURRENT HOST STATE: localhost;UP;HARD;1;PING OK - Packet loss = 0%, RTA = 0.06 ms
[1322110800] CURRENT HOST STATE: musewerx-72c7b0;UP;HARD;1;PING OK - Packet loss = 0%, RTA = 0.27 ms

我用代码是这样读的,

String strpath="/var/nagios.log";
FileReader fr = new FileReader(strpath);
BufferedReader br = new BufferedReader(fr);
String ch;
int time=0;
String Conversion="";
do {
    ch = br.readLine();
    out.print(ch+"<br/>"); 
} while (ch != null);
fr.close();

我更喜欢使用缓冲区读取器以相反的顺序读取

I would prefer to read in reverse order using buffer reader

推荐答案

据我所知,你试着逐行倒读.假设这是您尝试读取的文件:

As far as I understand, you try to read backwards line by line. Suppose this is the file you try to read:

line1
第2行
第3行

line1
line2
line3

并且您希望将其写入 servlet 的输出流,如下所示:

And you want to write it to the output stream of the servlet as follows:

line3
第2行
第1行

line3
line2
line1

在这种情况下,以下代码可能会有所帮助:

Following code might be helpful in this case:

    List<String> tmp = new ArrayList<String>();

    do {
        ch = br.readLine();
        tmp.add(ch);
        out.print(ch+"<br/>"); 
    } while (ch != null);

    for(int i=tmp.size()-1;i>=0;i--) {
        out.print(tmp.get(i)+"<br/>");
    }

这篇关于如何在Java中从头到尾(以相反的顺序)读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆