Problem with infinite loop RandomAccessFile

0

I am using this code to read a text file using RandomAccessFile , character by character, and generating a string for each word formed, to save in a HashMap. I need to use RandomAccessFile because I need to know the position of the word in the file, so I saved in my type registry this value offset = arq.getFilePointer()

The problem is that when I check in while(arq.read() != -1) the file pointer advances one position, so I always lose the first letter of my word. If I try to give a arq.seek() in the previous position, I even get the first letter again, but the program is in an infinite loop.

Is there any other way to control when the file reaches the end without using arq.read() ?

try {
RandomAccessFile arq = new RandomAccessFile("teste.txt", "r"); 
  try{ 
    while(arq.read() != -1) {
     String palavra = "";
     offset = arq.getFilePointer();
     letra = (char)arq.read(); 
        while (letra != ' ' && letra != '\n') {
          palavra += letra;
          letra = (char)arq.read();
        }
          palavra = palavra.toLowerCase();
          System.out.println(palavra); 
             if (h.PesquisaRegistro(palavra) == null) { 
                x = new Registro(palavra, offset);
                h.Inserir(x, h.HashCode(x));
             } else {
                x = h.PesquisaRegistro(palavra);
                x.quantidade++;
                h.tabela.replace(h.PesquisaChave(palavra), x);
             }
     }       
   }catch(EOFException ex){
   }       
} catch (IOException e) {
}
    
asked by anonymous 18.08.2017 / 04:58

2 answers

0

You could define a variable before the while and store the return of the first read in it.

While while :

RandomAccessFile arq = new RandomAccessFile("teste.txt", "r");
int letraByte = arq.read();
while (letraByte != -1){
    String palavra = "";

    while ((char) letraByte != ' ' && (char) letraByte != '\n' && letraByte != -1) {
        palavra += (char) letraByte;
        letraByte = arq.read();
    }

    letraByte = arq.read();
    System.out.println(palavra);
}

While do :

RandomAccessFile arq = new RandomAccessFile("teste.txt", "r");
int letraByte;
do {
    String palavra = "";
    letraByte = arq.read();

    while ((char) letraByte != ' ' && (char) letraByte != '\n' && letraByte != -1) {
        palavra += (char) letraByte;
        letraByte = arq.read();
    }
    System.out.println(palavra);
} while (letraByte != -1);
    
18.08.2017 / 19:19
0

You can simply call arq.read () before and at the end of the while and put the value into a variable and test that variable. So you can read the value later without walking the file pointer.

    
18.08.2017 / 05:19