1
I am making a program that needs to read a binary file and go extracting some information from it, what I have so far is the following:
public void processarArquivo() throws Exception{
try {
FileInputStream fileInputStream = new FileInputStream(ARQUIVO DE ENTRADA);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
DataInputStream objectIn = new DataInputStream(bufferedInputStream);
while (objectIn != null)
{
try {
String data = objectIn.readUTF();
char[]direcaoVento = objectIn.readChar();
int velocidadeVento = objectIn.readInt();
int indicePluviometrico = objectIn.readInt();
float temperatura = objectIn.readFloat();
}
catch(IOException e){
objectIn.close();
objectIn = null;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The mirror in my file is this:
Espelho do arquivo DadosMeteorologicos-Exemplo.dat
10/10/2015-E -1-15-19.8
11/10/2015-SE-38-16-15.1
12/10/2015-NW-69-4-15.6
13/10/2015-W -9-3-18.1
14/10/2015-NE-11-14-27.8
15/10/2015-SW-51-0-28.7
16/10/2015-NW-24-0-17.8
17/10/2015-E -11-12-16.1
18/10/2015-E -35-0-26.2
19/10/2015-W -42-8-15.8
20/10/2015-SE-14-17-21.7
21/10/2015-NW-51-0-26.0
22/10/2015-E -37-0-25.2
23/10/2015-SW-9-15-26.1
24/10/2015-NE-2-16-21.9
My question refers to while, is there any way to verify when I arrive at the end of the objectIn? Currently I simply have one while (true)
and wait for the program to fire a Exception
. But it seems wrong to me anyway.
Looks like it’s just capturing one
EOFException
while(true) same. Maybe if you add how the data is in that input file, we can suggest another alternative solution.– user28595
@Articuno That’s how I managed to do it, but you agree that it seems "wrong"?
– José Henrique Luckmann
If the documentation suggests, how can it be wrong? Adds a sample of the file in question if you want another read option.
– user28595
I hadn’t really seen that the documentation itself suggested this
– José Henrique Luckmann
How is this file? This mirror gives the impression that it is textual, with a variable number of lines and with fields separated by hyphen. Is it like that or is it binary? If it’s like I said, it’s easier to read line by line and break each one with a
String.split()
, then make the appropriate conversions from each field. It seems to me that theDataInputStream
is more for when you know the amount of information you want to extract from the file (usually binary or mixed).– Piovezan
@Suspect that it is not the intention of the documentation to suggest using the
EOFException
. The case is that a UTF character can be composed of more than one byte and aEOFException
exists to indicate that the reading of bytes expected to find say two bytes but was interrupted in the middle by aEOF
.– Piovezan
The file is binary, the mirror is just trying to expose what is the content to facilitate in understanding the code
– José Henrique Luckmann