writing arraylist of objects in file - java

I want to write arraylist of objects in a file. But only one object in going in file.Atfirst I am fetching all the stored objects and then appending new object after that I write whole arrayList to the file.
Here is my code....
public void write(UserDetail u1) throws FileNotFoundException {
ArrayList<UserDetail> al = new ArrayList<UserDetail>();
FileInputStream fin = new FileInputStream(FILEPATH);
try {
if (fin.available() != 0) {
ObjectInputStream ois = new ObjectInputStream(fin);
while (fin.available() != 0 && ois.available() != 0) {
try {
al.add((UserDetail) ois.readObject());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
}
}
}
}
al.add(u1);
FileOutputStream fos = new FileOutputStream(FILEPATH);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(al);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw e;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
help me......thnx in advance

You are reading object of type UserDetail but writing object of type ArrayList. Should probably be:
al = (ArrayList)ois.readObject ();
instead of
al.add ((UserDetail) ois.readObject ());

Related

Rewrite this code using try-with-resources

This code is used to copy an instance through java serialization. It uses the traditional try-catch-finally writing method. Can it be changed to try-with-resources form?(The DeepConcretePrototype in the code is an ordinary java object)
/**
* Clone an instance through java serialization
* #return
*/
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
//Output an instance to memory
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.flush();
//Read instance from memory
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(byteArrayInputStream);
clone = (DeepConcretePrototype)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return clone;
}
Yes you can use try-with-resources, but it's a little tricky because the success of read depends on the success of write. One way you can write it is with a nested try:
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
//Output an instance to memory
objectOutputStream.writeObject(this);
objectOutputStream.flush();
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
//Read instance from memory
clone = (DeepConcretePrototype) objectInputStream.readObject();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return clone;
}

StreamCorruptedException: invalid stream header: 79737200 when reading objects from a file

I create a client similarity, where clients register an account (an object is created) which is stored in a file.
Objects are written to the file as required, I override the writeStreamHeader() method. But when I try to read them all, their file throws an exception.
Write the objects to the file here.
public static void saveAccaunt(LoginAndPass gamers) {
boolean b = true;
FileInputStream fis = null;
try{
fis = new FileInputStream("student.ser");
fis.close();
}
catch (FileNotFoundException e)
{
b = false;
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream("student.ser",true);
ObjectOutputStream os = null;
if(b = true){
os = new AppendingObjectOutputStream(fileOutputStream);
System.out.println("Объект добавлен!");
}else {
os = new ObjectOutputStream(fileOutputStream);
System.out.println("Создан");
}
os.writeObject(gamers);
os.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("student.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
test = new ArrayList<>();
while (true){
test.add(objectInputStream.readObject());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(test.get(0));
}
Here is the error log for the exception thrown:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
at java.io.ObjectInputStream.(ObjectInputStream.java:358)
at Registratsiya.AllGamers.main(AllGamers.java:48)
Exception in thread "main" java.lang.NullPointerException
at Registratsiya.AllGamers.main(AllGamers.java:61)

Writing,reading and deleting objects into file in java

I want write list of objects into file, and then reading it one by one, and deleting respectively.
Writing and reading functions are below. For one by one reading,first I read all, then pop first, and other write to file again. it very ineffective and takes long time. So, what should I do to get better perfomance? Or maybe, there are other variant to solve this problem
public void writeToDisk(String filePath,TreeMap<String, ArrayList<Integer>> obj){
File file = new File(filePath);
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
ObjectOutputStream o = new ObjectOutputStream(fout);
o.writeObject(obj);
o.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TreeMap<String, ArrayList<Integer>> readFromDisk(String filePath){
TreeMap<String,ArrayList<Integer>> invertIndexMap = null;
File file = new File(filePath);
FileInputStream f;
try {
f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
invertIndexMap = (TreeMap<String, ArrayList<Integer>>) s.readObject();
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return invertIndexMap;
}

reading objects from file

I have a problem with reading objects from file Java.
file is anarraylist<projet>
This is the code of saving objects :
try {
FileOutputStream fileOut = new FileOutputStream("les projets.txt", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (projet a : file) {
out.writeObject(a);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
And this is the code of reading objects from file ::
try {
FileInputStream fileIn = new FileInputStream("les projets.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (in.available() > 0){
projet c = (projet) in.readObject();
b.add(c);
}
choisir = new JList(b.toArray());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Writing is working properly. The problem is the reading... it does not read any object (projet) What could be the problem?
As mentioned by EJP in comment and this SO post . if you are planning to write multiple objects in a single file you should write custom ObjectOutputStream , because the while writing second or nth object header information the file will get corrupt.
As suggested by EJP write as ArrayList , since ArrayList is already Serializable you should not have issue. as
out.writeObject(file) and read it back as ArrayList b = (ArrayList) in.readObject();
for some reason if you cant write it as ArrayList. create custome ObjectOutStream as
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
and change your writeObject as
try {
FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true);
MyObjectOutputStream out = new MyObjectOutputStream(fileOut );
for (projet a : file) {
out.writeObject(a);
}
out.close();
}
catch(Exception e)
{e.printStackTrace();
}
and change your readObject as
ObjectInputStream in = null;
try {
FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt");
in = new ObjectInputStream(fileIn );
while(true) {
try{
projet c = (projet) in.readObject();
b.add(c);
}catch(EOFException ex){
// end of file case
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

How can I convert a byte[] into ArrayList<CustomObjec>?

I receive a byte[] from my internal storage and now I don't know how to convert it into my ArrayList.
I'm referring to this post. -->>THIS<<--
snipped code:
ArrayList<KFZInfo> toReturn = null;
FileInputStream fis;
try {
fis = openFileInput("kfzList");
ObjectInputStream oi = new ObjectInputStream(fis);
toReturn = (ArrayList<KFZInfo>) oi.readObject();
oi.close();
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
At toReturn = (ArrayList<KFZInfo>) oi.readObject(); it is throwing an error which says: java.lang.ClassCastException: byte[] cannot be cast to java.utio.ArrayList
And thats how I write it on the internal storage:
try {
FileOutputStream fos = openFileOutput("kfzList", Context.MODE_PRIVATE);
ObjectOutputStream oo = new ObjectOutputStream(fos);
oo.writeObject(listKfzInfo.toString().getBytes());
oo.flush();
oo.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
How do I solve this problem?
Change
oo.writeObject(listKfzInfo.toString().getBytes());
with
oo.writeObject(listKfzInfo);
I assuming that listKfzInfo is an ArrayList<KFZInfo> and that KFZInfo implements Serializable and that all fields inside KFZInfo implements Serializable

Categories

Resources