Подтвердить что ты не робот

Как читать файл с конца до начала (в обратном порядке) в Java?

Я хочу прочитать файл в противоположном направлении от конца до начала моего файла,

[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();

Я бы предпочел читать в обратном порядке с помощью буферизатора

4b9b3361

Ответ 1

Насколько я понимаю, вы пытаетесь читать назад за строкой. Предположим, что это файл, который вы пытаетесь прочитать:

line1
line2
line3

И вы хотите записать его в выходной поток сервлета следующим образом:

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

Ответ 2

У меня была такая же проблема, как описано здесь. Я хочу посмотреть строки в файле в обратном порядке, от конца до начала (команда 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();
        }
    }
}

Ответ 3

Apache Commons IO имеет ReversedLinesFileReader класс для этого сейчас (ну, начиная с версии 2.2).

Таким образом, ваш код может быть:

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

Ответ 4

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;
        }
    }
}

Ответ 5

Предлагаемый ReverseLineInputStream работает действительно медленно, когда вы пытаетесь читать тысячи строк. На моем ПК Intel Core i7 на SSD-диске он составлял около 60 тыс. Строк за 80 секунд. Вот вдохновленная оптимизированная версия с буферизованным чтением (напротив однократного чтения в ReverseLineInputStream). Файл журнала 60k строк читается за 400 миллисекунд:

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;
        }
    }
}}

Ответ 6

@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, и это ничего, кроме тривиального.