Reputation: 393
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
Upvotes: 1
Views: 1240
Reputation: 164
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
Upvotes: 1
Reputation: 18633
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 String
s 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?.
Upvotes: 0