3

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;
}
3
  • Can you post some sample data please? @Becca Commented Aug 8, 2017 at 16:43
  • 1
    I would expect the while loop in the first code snippet to be infinite, since read is never read from, so it should always have data remaining. Commented Aug 8, 2017 at 16:43
  • You don't need to, and shouldn't use available(). It doesn't do what you think it does. Commented Aug 8, 2017 at 16:47

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

It worked! For whatever reason, though, only the first song listed in the binary file is getting printed to the console. Any idea why?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.