Reading data from a binary file (Java)?
For a class I'm working on, I need to create a program that writes binary data to a file (based on user input) and then reads it to the console. This is done with two separate programs that process the data and receive user input. Whenever I try to list the contents of the file, it prints the last item over and over. What's the problem with my code?
Here's the relevant part of the program that handles user input and fingerprint on the console:
String song = null;
try
{
DataInputStream read = new DataInputStream(
new FileInputStream( fileName ));
while( read.available() > 0 )
{
song = process.readSong( fileName );
System.out.println( song );
}
}
catch( Exception e )
{
System.out.println( "Error" );
}
Here's the relevant part of the program that processes the data and reads it from the binary:
public String readSong( String fileName )
{
DataInputStream in = null;
String sTitle;
String sArtist;
String sGenre;
String song = null;
try
{
in = new DataInputStream(
new BufferedInputStream(
new FileInputStream( fileName )));
sTitle = in.readUTF();
sArtist = in.readUTF();
sGenre = in.readUTF();
song = sTitle + "\t" + sArtist + "\t" + sGenre;
in.close();
}
catch( Exception ex )
{
System.out.println( "Error" );
}
return song;
}
source to share
Your object DataInputStream
never changes because it DataInputStream in
is local to the function readSong()
.
You need to pass the reference of your DataInputStream
object to read in the function readSong()
.
So the call should be song = process.readSong( fileName , read );
and remove the local DataInputStream in
from your functionreadSong()
source to share