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) {
}