如何在Java中从头到尾读取文件(以相反的顺序)?

时间:2011-12-29 06:34:14

标签: java 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();

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

7 个答案:

答案 0 :(得分:55)

我遇到了与此处描述的问题相同的问题。我想以相反的顺序查看文件中的行,从结尾返回到开始(unix tac命令将执行此操作)。

但是我的输入文件相当大,所以将整个文件读入内存,因为在其他示例中对我来说并不是一个可行的选项。

下面是我提出的类,它使用RandomAccessFile,但不需要任何缓冲区,因为它只保留指向文件本身的指针,并使用标准的InputStream方法。

它适用于我的案例,空文件和我尝试过的其他一些东西。现在我没有Unicode字符或任何花哨的东西,但只要这些行由LF分隔,即使它们有LF + CR也应该有效。

基本用法是:

in = new BufferedReader (new InputStreamReader (new ReverseLineInputStream(file)));

while(true) {
    String line = in.readLine();
    if (line == null) {
        break;
    }
    System.out.println("X:" + line);
}

以下是主要来源:

package www.kosoft.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

public class ReverseLineInputStream extends InputStream {

    RandomAccessFile in;

    long currentLineStart = -1;
    long currentLineEnd = -1;
    long currentPos = -1;
    long lastPosInFile = -1;

    public ReverseLineInputStream(File file) throws FileNotFoundException {
        in = new RandomAccessFile(file, "r");
        currentLineStart = file.length();
        currentLineEnd = file.length();
        lastPosInFile = file.length() -1;
        currentPos = currentLineEnd; 
    }

    public void findPrevLine() throws IOException {

        currentLineEnd = currentLineStart; 

        // There are no more lines, since we are at the beginning of the file and no lines.
        if (currentLineEnd == 0) {
            currentLineEnd = -1;
            currentLineStart = -1;
            currentPos = -1;
            return; 
        }

        long filePointer = currentLineStart -1;

         while ( true) {
             filePointer--;

            // we are at start of file so this is the first line in the file.
            if (filePointer < 0) {  
                break; 
            }

            in.seek(filePointer);
            int readByte = in.readByte();

            // We ignore last LF in file. search back to find the previous LF.
            if (readByte == 0xA && filePointer != lastPosInFile ) {   
                break;
            }
         }
         // we want to start at pointer +1 so we are after the LF we found or at 0 the start of the file.   
         currentLineStart = filePointer + 1;
         currentPos = currentLineStart;
    }

    public int read() throws IOException {

        if (currentPos < currentLineEnd ) {
            in.seek(currentPos++);
            int readByte = in.readByte();
            return readByte;

        }
        else if (currentPos < 0) {
            return -1;
        }
        else {
            findPrevLine();
            return read();
        }
    }
}

答案 1 :(得分:18)

Apache Commons IO现在具有ReversedLinesFileReader类(从版本2.2开始)。

所以你的代码可能是:

var gui = function(){
    var window = function(){
        console.log("I'm alive");
    }   

    return {"window" : window() }
}

var instance = new gui.window();

答案 2 :(得分:10)

上面发布的ReverseLineInputStream正是我想要的。我正在阅读的文件很大,无法缓冲。

有一些错误:

  • 文件未关闭
  • 如果最后一行未终止,则在第一次读取时返回最后两行。

以下是更正后的代码:

package www.kosoft.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

public class ReverseLineInputStream extends InputStream {

    RandomAccessFile in;

    long currentLineStart = -1;
    long currentLineEnd = -1;
    long currentPos = -1;
    long lastPosInFile = -1;
    int lastChar = -1;


    public ReverseLineInputStream(File file) throws FileNotFoundException {
        in = new RandomAccessFile(file, "r");
        currentLineStart = file.length();
        currentLineEnd = file.length();
        lastPosInFile = file.length() -1;
        currentPos = currentLineEnd; 

    }

    private void findPrevLine() throws IOException {
        if (lastChar == -1) {
            in.seek(lastPosInFile);
            lastChar = in.readByte();
        }

        currentLineEnd = currentLineStart; 

        // There are no more lines, since we are at the beginning of the file and no lines.
        if (currentLineEnd == 0) {
            currentLineEnd = -1;
            currentLineStart = -1;
            currentPos = -1;
            return; 
        }

        long filePointer = currentLineStart -1;

        while ( true) {
            filePointer--;

            // we are at start of file so this is the first line in the file.
            if (filePointer < 0) {  
                break; 
            }

            in.seek(filePointer);
            int readByte = in.readByte();

            // We ignore last LF in file. search back to find the previous LF.
            if (readByte == 0xA && filePointer != lastPosInFile ) {   
                break;
            }
        }
        // we want to start at pointer +1 so we are after the LF we found or at 0 the start of the file.   
        currentLineStart = filePointer + 1;
        currentPos = currentLineStart;
    }

    public int read() throws IOException {

        if (currentPos < currentLineEnd ) {
            in.seek(currentPos++);
            int readByte = in.readByte();            
            return readByte;
        } else if (currentPos > lastPosInFile && currentLineStart < currentLineEnd) {
            // last line in file (first returned)
            findPrevLine();
            if (lastChar != '\n' && lastChar != '\r') {
                // last line is not terminated
                return '\n';
            } else {
                return read();
            }
        } else if (currentPos < 0) {
            return -1;
        } else {
            findPrevLine();
            return read();
        }
    }

    @Override
    public void close() throws IOException {
        if (in != null) {
            in.close();
            in = null;
        }
    }
}

答案 3 :(得分:9)

当您尝试读取数千行时,建议的ReverseLineInputStream非常。在我的PC 英特尔酷睿i7在SSD驱动器上它在80秒内大约有6万行。以下是带有缓冲读取的灵感优化版本(与ReverseLineInputStream中的一次一字节读取相反)。在400毫秒内读取60k行日志文件:

public class FastReverseLineInputStream extends InputStream {

private static final int MAX_LINE_BYTES = 1024 * 1024;

private static final int DEFAULT_BUFFER_SIZE = 1024 * 1024;

private RandomAccessFile in;

private long currentFilePos;

private int bufferSize;
private byte[] buffer;
private int currentBufferPos;

private int maxLineBytes;
private byte[] currentLine;
private int currentLineWritePos = 0;
private int currentLineReadPos = 0;
private boolean lineBuffered = false;

public ReverseLineInputStream(File file) throws IOException {
    this(file, DEFAULT_BUFFER_SIZE, MAX_LINE_BYTES);
}

public ReverseLineInputStream(File file, int bufferSize, int maxLineBytes) throws IOException {
    this.maxLineBytes = maxLineBytes;
    in = new RandomAccessFile(file, "r");
    currentFilePos = file.length() - 1;
    in.seek(currentFilePos);
    if (in.readByte() == 0xA) {
        currentFilePos--;
    }
    currentLine = new byte[maxLineBytes];
    currentLine[0] = 0xA;

    this.bufferSize = bufferSize;
    buffer = new byte[bufferSize];
    fillBuffer();
    fillLineBuffer();
}

@Override
public int read() throws IOException {
    if (currentFilePos <= 0 && currentBufferPos < 0 && currentLineReadPos < 0) {
        return -1;
    }

    if (!lineBuffered) {
        fillLineBuffer();
    }


    if (lineBuffered) {
        if (currentLineReadPos == 0) {
            lineBuffered = false;
        }
        return currentLine[currentLineReadPos--];
    }
    return 0;
}

private void fillBuffer() throws IOException {
    if (currentFilePos < 0) {
        return;
    }

    if (currentFilePos < bufferSize) {
        in.seek(0);
        in.read(buffer);
        currentBufferPos = (int) currentFilePos;
        currentFilePos = -1;
    } else {
        in.seek(currentFilePos);
        in.read(buffer);
        currentBufferPos = bufferSize - 1;
        currentFilePos = currentFilePos - bufferSize;
    }
}

private void fillLineBuffer() throws IOException {
    currentLineWritePos = 1;
    while (true) {

        // we've read all the buffer - need to fill it again
        if (currentBufferPos < 0) {
            fillBuffer();

            // nothing was buffered - we reached the beginning of a file
            if (currentBufferPos < 0) {
                currentLineReadPos = currentLineWritePos - 1;
                lineBuffered = true;
                return;
            }
        }

        byte b = buffer[currentBufferPos--];

        // \n is found - line fully buffered
        if (b == 0xA) {
            currentLineReadPos = currentLineWritePos - 1;
            lineBuffered = true;
            break;

            // just ignore \r for now
        } else if (b == 0xD) {
            continue;
        } else {
            if (currentLineWritePos == maxLineBytes) {
                throw new IOException("file has a line exceeding " + maxLineBytes
                        + " bytes; use constructor to pickup bigger line buffer");
            }

            // write the current line bytes in reverse order - reading from
            // the end will produce the correct line
            currentLine[currentLineWritePos++] = b;
        }
    }
}}

答案 4 :(得分:4)

据我了解,您尝试逐行向后阅读。 假设这是您尝试阅读的文件:

LINE1
2号线
line3中

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

line3中
2号线
LINE1

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

    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/>");
    }

答案 5 :(得分:2)

@Test
public void readAndPrintInReverseOrder() throws IOException {

    String path = "src/misctests/test.txt";

    BufferedReader br = null;

    try {
        br = new BufferedReader(new FileReader(path));
        Stack<String> lines = new Stack<String>();
        String line = br.readLine();
        while(line != null) {
            lines.push(line);
            line = br.readLine();
        }

        while(! lines.empty()) {
            System.out.println(lines.pop());
        }

    } finally {
        if(br != null) {
            try {
                br.close();   
            } catch(IOException e) {
                // can't help it
            }
        }
    }
}

请注意,此代码将孔文件读入内存,然后开始打印。这是使用缓冲读卡器或不支持搜索的其他读卡器的唯一方法。你必须记住这一点,在你想要读取日志文件的情况下,日志文件可能会非常大!

如果你想逐行阅读并在飞行中打印,那么除了使用支持java.io.RandomAccessFile之类的阅读器之外别无选择,除此之外别无他法。

答案 6 :(得分:0)

我的解决方案@dpetruha因此而出现问题:

Does RandomAccessFile.read() from local file guarantee that exact number of bytes will be read?

这是我的解决方案:(仅更改了fillBuffer)

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

public class ReverseLineInputStream extends InputStream {

    private static final int MAX_LINE_BYTES = 1024 * 1024;
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 1024;

    private RandomAccessFile in;
    private long currentFilePos;
    private int bufferSize;
    private byte[] buffer;
    private int currentBufferPos;
    private int maxLineBytes;
    private byte[] currentLine;
    private int currentLineWritePos = 0;
    private int currentLineReadPos = 0;
    private boolean lineBuffered = false;

    public ReverseLineInputStream(File file) throws IOException {
        this(file, DEFAULT_BUFFER_SIZE, MAX_LINE_BYTES);
    }

    public ReverseLineInputStream(File file, int bufferSize, int maxLineBytes) throws IOException {
        this.maxLineBytes = maxLineBytes;
        in = new RandomAccessFile(file, "r");
        currentFilePos = file.length() - 1;
        in.seek(currentFilePos);
        if (in.readByte() == 0xA) {
            currentFilePos--;
        }
        currentLine = new byte[maxLineBytes];
        currentLine[0] = 0xA;

        this.bufferSize = bufferSize;
        buffer = new byte[bufferSize];
        fillBuffer();
        fillLineBuffer();
    }

    @Override
    public int read() throws IOException {
        if (currentFilePos <= 0 && currentBufferPos < 0 && currentLineReadPos < 0) {
            return -1;
        }

        if (!lineBuffered) {
            fillLineBuffer();
        }

        if (lineBuffered) {
            if (currentLineReadPos == 0) {
                lineBuffered = false;
            }
            return currentLine[currentLineReadPos--];
        }
        return 0;
    }

    private void fillBuffer() throws IOException {
        if (currentFilePos < 0) {
            return;
        }

        if (currentFilePos < bufferSize) {
            in.seek(0);
            buffer = new byte[(int) currentFilePos + 1];
            in.readFully(buffer);
            currentBufferPos = (int) currentFilePos;
            currentFilePos = -1;
        } else {
            in.seek(currentFilePos - buffer.length);
            in.readFully(buffer);
            currentBufferPos = bufferSize - 1;
            currentFilePos = currentFilePos - bufferSize;
        }
    }

    private void fillLineBuffer() throws IOException {
        currentLineWritePos = 1;
        while (true) {

            // we've read all the buffer - need to fill it again
            if (currentBufferPos < 0) {
                fillBuffer();

                // nothing was buffered - we reached the beginning of a file
                if (currentBufferPos < 0) {
                    currentLineReadPos = currentLineWritePos - 1;
                    lineBuffered = true;
                    return;
                }
            }

            byte b = buffer[currentBufferPos--];

            // \n is found - line fully buffered
            if (b == 0xA) {
                currentLineReadPos = currentLineWritePos - 1;
                lineBuffered = true;
                break;

                // just ignore \r for now
            } else if (b == 0xD) {
                continue;
            } else {
                if (currentLineWritePos == maxLineBytes) {
                    throw new IOException("file has a line exceeding " + maxLineBytes
                            + " bytes; use constructor to pickup bigger line buffer");
                }

                // write the current line bytes in reverse order - reading from
                // the end will produce the correct line
                currentLine[currentLineWritePos++] = b;
            }
        }
    }

}