how to write/read multiple object arrays using a text file [Java] - java

I want to write 3 object arrays to the same text file and load the data back to the arrays as well. However, I can only seem to get this to work with arr1 with the below code. How can I change this code to write the data of all 3 arrays to the same file and load the data back to their respective arrays?
import java.io.*;
public class CarCenter implements Serializable {
static CarCenter[] arr1 = new CarCenter[6];
static CarCenter[] arr2 = new CarCenter[6];
static CarCenter[] arr3 = new CarCenter[6];
public static void write() {
try {
FileOutputStream fos = new FileOutputStream("Data.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arr1);
oos.writeObject(arr2);
oos.writeObject(arr3);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void load() {
try {
FileInputStream fis = new FileInputStream("Data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
CarCenter[] saved = (CarCenter[]) ois.readObject();
arr1 = saved;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

In your code you are only loading the value of arr1:
public static void load() {
try {
FileInputStream fis = new FileInputStream("Data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
CarCenter[] saved = (CarCenter[]) ois.readObject();
arr1 = saved;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
All you have to do is to read the other objects as well like this:
public static void load() {
try {
FileInputStream fis = new FileInputStream("Data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
CarCenter[] saved = (CarCenter[]) ois.readObject();
arr1 = saved;
CarCenter[] saved2 = (CarCenter[]) ois.readObject();
arr2 = saved2;
CarCenter[] saved3 = (CarCenter[]) ois.readObject();
arr3 = saved3;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
Want to learn more?
I suggest reading the documentation itself.

Related

Appendable Binary File

I'm working on appending objects to a binary file. My file is:
File f=new File("person.dat");
I'm getting an error (java.io.StreamCorruptedException: invalid stream header: 79737200) when I attempt to open the binary file. As far as I can tell the program writes the data just fine, but as soon as I try reading from it, I get the above error. Any help is appreciated!
My Code to write:
AppendObjectOutputStream out = null;
try {
out = new AppendObjectOutputStream(new FileOutputStream(f, true));
out.writeObject(new Student(name, age));
out.flush();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
out.close();
}
My class for making appendable:
public class AppendObjectOutputStream extends ObjectOutputStream {
public AppendObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
#Override
protected void writeStreamHeader() throws IOException {
reset();
}
}
My partial code for reading and adding objects to an ArrayList:
Course course = new Course();
Student st = null;
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("person.dat"));
try
{
while (true)
{
st = (Student) in.readObject();
course.addAccount(st); //adds student object to an ArrayList in
//class Course
}
}
catch (EOFException ex) {
}
}
catch (Exception ex) {
ex.printStackTrace();
} finally {
in.close();
}
UPDATE:
Current code to read but its not printing anything to screen:
try(ObjectInputStream ois = new ObjectInputStream(
new BufferedInputStream(Files.newInputStream(f))))
{
while (ois.available() > 0)
{
st = (Student) ois.readObject();
studentlist.addAccount(st);
System.out.println(st.getStudentNumber());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
This is how I write to file:
Path f = Paths.get("person.dat");
try (ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(f, StandardOpenOption.APPEND))))
{
oos.writeObject(new Student(name,age));
}
catch(Exception ex)
{
ex.printStackTrace();
}
Rather than trying to fix your utility classes, I suggest to use the standard classes of the NIO.2 File API.
Try something like (untested):
Path personDataFilePath = Paths.get("person.dat");
// or Java 11:
// Path personDataFilePath = Path.of("person.dat");
try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(personDataFilePath, StandardOpenOption.APPEND)))){
oos.writeObject(new Student(name,age));
} catch (IOException ex) {
// do some error handling here
}
and to read the file, something like (untested):
List<Student> students = new ArrayList<>();
try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(personDataFilePath)))){
while (ois.available() > 0){
students.add((Student) ois.readObject());
}
} catch (IOException ex) {
// do some error handling here
}
I have modified the code to work around making a file "appendable". I write a single arraylist object to the file (the arraylist holds a list of student objects). When I want to add a student, I read the object (arraylist) from the file, add my new student to the arraylist and write the arraylist back to the file. It is now working and my file does not have an append format.

Loading object and displaying data

I made a class that saves and loads objects for my Othello game project. My question is how do I take this saved object and display the saved game board state within it? Thanks in advance for the answers by the way!
public class SaveGame {
public static final String filename = "gameSave.bin";
public void saveGameFile(Serializable object){
FileOutputStream fs = null;
try{
fs = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(object);
os.flush();
os.close();
}catch(IOException e){
e.printStackTrace();
}
}
public void load(){
if(checkFileExists()){
FileInputStream fis = null;
try{
fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
CreateBoard cb = (CreateBoard) ois.readObject();
ois.close();
System.out.println(cb.toString());
}catch(ClassNotFoundException | IOException e){
e.printStackTrace();
}
}
}
public boolean checkFileExists(){
return new File(filename).isFile(); //Searches directory to make sure file exists
}

Can I serialize an arraylist so that I can store it in a .dat file?

I'm trying to store an arraylist of a type I made, inside of a dat file so that the data isn't lost every time I close the program. I've never done anything with serialization before, from looking at other questions on this site I think it's what I want. Any help or insight is vastly appreciated!
ArrayList implements Serializable ,So you can serialize it. But remember that ArrayList is just a collection of items, so make sure that all the items are also serializable. Here is an example
import java.util.ArrayList;
import java.io.*;
public class ListSerExample {
public static void main(String[] args) {
ArrayList<String> lst = new ArrayList<>();
lst.add("a");
lst.add("b");
lst.add("c");
try (FileOutputStream fos = new FileOutputStream("foo.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(lst);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> deserialized= new ArrayList<>();
try (FileInputStream fis = new FileInputStream("foo.dat");
ObjectInputStream ois = new ObjectInputStream(fis);){
deserialized = (ArrayList) ois.readObject();
ois.close();
fis.close();
System.out.println("deserialized = " + deserialized);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

reading the serializable objects from file

List ll=new LinkedList();
Student temp;
int size = obj.readInt();
System.out.println(size);
for (int i = 0; i <size; ++i) {
ll.add((Student) obj.readObject());
}
obj.close();
System.out.println(ll);
}
it causes the run time exception as
"Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at p1.DeSerializeDemo1.main(DeSerializeDemo1.java:18)"
Please give me solution for this.
EOFException in ObjectInputStream.readInt means that there are less than 4 bytes left in the file after current position.
Just handle the Exception
try{
int size = obj.readInt();
}catch(EOFException ex){}
Why don't you create a class and save/load the entire object (that class needs to implement Serializable though (and all objects used it that class too)), then get the information you want using that object you can cast it afterwards:
public static Object load(String path) throws FileNotFoundException, Exception {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) {
final Object result = ois.readObject();
ois.close();
return result;
}
}
public static void save(Object obj, String path) throws Exception {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
oos.writeObject(obj);
oos.flush();
oos.close();
}
}
Exception cause is that you are not calling ObjectOutputStream.writeInt(int) before writing objects. As far as I understand you are trying to store number of objects, which is stored in the file. So, you should do it like this: obj.writeInt(2);
public class Test implements Serializable {
private static final long serialVersionUID = 243705916609512381L;
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
Test s = new Test();
s.setName("Test");
Test s1 = new Test();
s1.setName("Test 2");
ObjectOutputStream oos = null;
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
ObjectInputStream ois = null;
try {
fileOutputStream = new FileOutputStream("C:\\test.txt");
oos = new ObjectOutputStream(fileOutputStream);
oos.writeInt(2);
oos.writeObject(s1);
oos.writeObject(s);
oos.flush();
oos.close();
fileOutputStream.close();
fileInputStream = new FileInputStream("C:\\test.txt");
ois = new ObjectInputStream(fileInputStream);
int readInt = ois.readInt();
System.out.println("Read int " + readInt);
Test readObject = (Test) ois.readObject();
System.out.println(readObject.getName());
Test readObject2 = (Test) ois.readObject();
System.out.println(readObject2.getName());
ois.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// close everything
}
}

How to write and read java serialized objects into a file

I am going to write multiple objects to a file and then retrieve them in another part of my code. My code has no error, but it is not working properly. Could you please help me find what is wrong about my code.
I read different codes from different websites, but none of them worked for me!
Here is my code to write my objects to a file:
MyClassList is an arraylist which includes objects of my class (which must be written to a file).
for (int cnt = 0; cnt < MyClassList.size(); cnt++) {
FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList.get(cnt));
}
I added "true" to the constructor of the outputstream, because I want to add each object to end of the file. Is that correct?
And here is my code to read the objects from the file:
try {
streamIn = new FileInputStream("G:\\address.ser");
ObjectInputStream objectinputstream = new ObjectInputStream(streamIn);
MyClass readCase = (MyClass) objectinputstream.readObject();
recordList.add(readCase);
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
}
It finally prints out just one object. Now, I don't know if I am not writing correctly or reading correctly!
Why not serialize the whole list at once?
FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);
Assuming, of course, that MyClassList is an ArrayList or LinkedList, or another Serializable collection.
In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.
As others suggested, you can serialize and deserialize the whole list at once, which is simpler and seems to comply perfectly with what you intend to do.
In that case the serialization code becomes
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
fout = new FileOutputStream("G:\\address.ser", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(myClassList);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(oos != null){
oos.close();
}
}
And deserialization becomes (assuming that myClassList is a list and hoping you will use generics):
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream("G:\\address.ser");
objectinputstream = new ObjectInputStream(streamIn);
List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
recordList.add(readCase);
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
objectinputstream .close();
}
}
You can also deserialize several objects from a file, as you intended to:
ObjectInputStream objectinputstream = null;
try {
streamIn = new FileInputStream("G:\\address.ser");
objectinputstream = new ObjectInputStream(streamIn);
MyClass readCase = null;
do {
readCase = (MyClass) objectinputstream.readObject();
if(readCase != null){
recordList.add(readCase);
}
} while (readCase != null)
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
objectinputstream .close();
}
}
Please do not forget to close stream objects in a finally clause (note: it can throw exception).
EDIT
As suggested in the comments, it should be preferable to use try with resources and the code should get quite simpler.
Here is the list serialization :
try(
FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
){
oos.writeObject(myClassList);
} catch (Exception ex) {
ex.printStackTrace();
}
Simple program to write objects to file and read objects from file.
package program;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class TempList {
public static void main(String[] args) throws Exception {
Counter counter = new Counter(10);
File f = new File("MyFile.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(counter);
oos.close();
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Counter newCounter = (Counter) ois.readObject();
System.out.println(newCounter.count);
ois.close();
}
}
class Counter implements Serializable {
private static final long serialVersionUID = -628789568975888036 L;
int count;
Counter(int count) {
this.count = count;
}
}
After running the program the output in your console window will be 10 and you can find the file inside Test folder by clicking on the icon show in below image.
I think you have to write each object to an own File or you have to split the one when reading it.
You may also try to serialize your list and retrieve that when deserializing.
if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.
Serialization:
LinkedList<YourObject> listOfObjects = <something>;
try {
FileOutputStream file = new FileOutputStream(<filePath>);
ObjectOutputStream writer = new ObjectOutputStream(file);
for (YourObject obj : listOfObjects) {
writer.writeObject(obj);
}
writer.close();
file.close();
} catch (Exception ex) {
System.err.println("failed to write " + filePath + ", "+ ex);
}
De-serialization:
try {
FileInputStream file = new FileInputStream(<filePath>);
ObjectInputStream reader = new ObjectInputStream(file);
while (true) {
try {
YourObject obj = (YourObject)reader.readObject();
System.out.println(obj)
} catch (Exception ex) {
System.err.println("end of reader file ");
break;
}
}
} catch (Exception ex) {
System.err.println("failed to read " + filePath + ", "+ ex);
}

Categories

Resources