Having a ArrayList>, how do I serialize?
ArrayList<ArrayList<MyPoint>> polygons;
try {
FileOutputStream fileOut = openFileOutput("polygons.ser", MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(pv.polygons);
out.close();
fileOut.close();
Log.d("Polygons Output", pv.polygons.toString());
Log.d("Polygons Output Out", out.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileIn = openFileInput("polygons.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<ArrayList<MyPoint>> arr = new ArrayList<>();
pv.polygons = (ArrayList<ArrayList<MyPoint>>) in.readObject();
in.close();
fileIn.close();
} catch (IOException io) {
io.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Log.d shows me ArrayList of [[Point(0,0) ,....]].
The outputStream is in onSaveInstance and the inputStream is in onCreate().
MyPoint extends Point implements Serializable...
Why does it not work?
Related
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;
}
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)
I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}
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;
}
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