For a class I'm working on, I have 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, one that processes data and one that gets 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 processes user input and prints to 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 data and reads it from the binary file:
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;
}
Your DataInputStream object is never modified, because DataInputStream in is local to function readSong().
You need to pass a reference of your DataInputStream object read in the function readSong().
So the call should be song = process.readSong( fileName , read ); and remove the local DataInputStream in from your function readSong()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With