2

Meu objetivo é ler um arquivo (linha por linha), porém, iniciando pelo final do arquivo (ultima linha) até o início (primeira linha).

Alguém poderia dar uma possível ideia de realizar esse procedimento?

Estava usando RandomAcessFile com o intuito de utilizar o seek para o final do arquivo e ir voltando, porém não deu muito certo.

2
  • 1
    Até é possível, mas acho que vai ficar uma gambiarra enorme. Você tem a necessidade de fazer desse jeito? Pois o ideal seria você ler o arquivo inteiro e depois ir pegando as linhas de trás para frente. Dá uma olhada nesse tópico: Como rebobinar o ponteiro de arquivo corretamente em Java?
    – Math
    23/09/2015 às 11:59
  • 1
    Se forem arquivos muito grandes, e linhas de tamanho variáveis, eu sugeriria uma "lida" pra frente para indexar as linhas e posição, e usar o seek com o índice pronto na volta. Tem casos legítimos pra isso, em situações em que o arquivo não caberia todo na memória sem penalidade de performance e o processamento linha a linha realmente tenha que ser inverso. Mas há uma grande probabilidade de não ser o seu caso específico. Outra saída para situação similar, é ler o arquivo em blocos fixos, de por exemplo 8K em 8K, do fim pro começo, e você escanear as quebras das linhas em cada bloco.
    – Largato
    25/06/2016 às 23:01

2 Respostas 2

1

Files#readAllLines te retorna uma lista com todas as linhas do arquivo. Então pode usar Collections.reverse para inverter a ordem dessa lista:

List<String> linhas = Files.readAllLines(Paths.get("foo/bar.txt"));
Collections.reverse(linhas);

Pode usar List#get para obter cada linha do arquivo posteriormente: linhas.get(0); (que devolveria a primeira linha) retornará a última, e assim por diante...

Funcionando no Repl.it

0

Aqui está a implementação:

 /**
 * Input stream utilizado para ler um arquivo em ordem reversa
 * http://stackoverflow.com/questions/8664705/how-to-read-file-from-end-to-start
 * -in-reverse-order-in-java
 *
 *
 */
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();
        }
    }

    @Override
    public void close() throws IOException {
        super.close();
        in.close();
    }
}

Usando ele:

ReverseLineInputStream reverseLineInputStream = new RverseLineInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(reverseLineInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String readLine = bufferedReader.readLine();
1

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .