Becca
Becca

Reputation: 35

Reading data from binary file (Java)?

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;
}

Upvotes: 3

Views: 1373

Answers (2)

Sumeet
Sumeet

Reputation: 8292

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()

Upvotes: 1

user2862544
user2862544

Reputation: 425

put while loop in readSong method then only it will read file line by line. while loop is not required in first method you just need to pass filename to readsong method.

Upvotes: 0

Related Questions