1

I've noticed that whenever you use FileOutputStream with append as true, the object that is appended is placed on a different line.

My question is how do you read multiple lines of data with ObjectInputStream.

For ex:

public class StringBytes {

    public static void main(String[] args) throws Exception {
        String S1 = "Hi";
        String S2 = "\n"+"Bye";
        String file = "C:\\HiBye.out";


        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(S1);

        fileOutputStream = new FileOutputStream(file,true);
        objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(S2);



        FileInputStream fileInputStream = new FileInputStream(file);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        String SS = (String) objectInputStream.readObject();
        System.out.println(SS);

    }
}

The output for the above is Hi since Bye is on a different line it is not read. I'm still a beginer so all help appreciated

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
Raicky Derwent
  • 384
  • 1
  • 4
  • 14

2 Answers2

1

You wrote two objects (instances of String) into the file: s1 and s2. You read only one object, the first.

If you want it to be treated as a single String, you need s1 to be "Hey" + \n + "Bye". Alternatively, you can call readObject() twice, and get the second object

Tom S.
  • 164
  • 6
  • How do you go about it if you dont know how many lines there are ? How would you iterate through the file ? – Raicky Derwent Nov 18 '13 at 10:47
  • you can surround it with try ans catch EOFException, and iterate until it fails. There are other ways tough. Here are some good answers: http://stackoverflow.com/questions/2626163/java-fileinputstream-objectinputstream-reaches-end-of-file-eof – Tom S. Nov 18 '13 at 11:01
0

With ObjectOutputStream and ObjectInputStream, everything is stored in the file in a binary format, so looking at the file won't give you that much information.

What you put into the file and what you get out of the input stream afterwards are individual objects. To get both Strings you'd need to call readObject() twice, once for each writeObject() you had initially.

If you want to work with text files, you could take a look at BufferedReader and BufferedWriter. If you're interested in reading an entire text file at once, take a look at What is simplest way to read a file into String?.

Community
  • 1
  • 1
Vlad
  • 18,195
  • 4
  • 41
  • 71