Deserialize only if a serialized file exists - java

I have my program setup to serialize a certain Facebook Object on exit, and deserialize it on open. But I want to have an if statement in the deserialization portion to only go on with it if a serilization file is present to avoid errors. How can I do that? Is there anyway that I could refer to the file "serilaized" and check if it exists?
Deserialization portion:
Facebook facebook = null;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"serialized"));
facebook = (Facebook) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
System.err.println("Could not open the file \"serialized\"");
} catch (IOException e) {
System.err.println("Could not de-serialize the object");
} catch (ClassNotFoundException e) {
System.err.println("Could not cast the de-serialized object");
}
Serialization portion:
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream ("serialized"));
oos.writeObject(facebook);
oos.close();
} catch (FileNotFoundException e) {
System.err
.println("Could not create the file \"serialized\"");
} catch (IOException e) {
System.err.println("Could not serialize the object");
}

The FileNotFoundException should catch the case where there is no file present to deserialize. Throwing the error is fine, so long as it is handled gracefully.

Related

local class incompatible error

The following code gives me the error InvalidClassException My User class implements Serializable so I'm lost. I'm trying to store list filled with User objects and then be able to read it back.
List<User> userList = new ArrayList<User>();//list used
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName, true));
os.writeObject(userList);
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
// input
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
userList = (List<User>) ois.readObject();
ois.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
If you are trying to store and later retrieve a single object (a List<> in your example) in a file, you do not want to append to the file each time you write to it. Rather, you want to overwrite the file each time, with the new object.
// Write
List<User> userList = new ArrayList<User>();
try (FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(userList);
} catch (IOException e1) {
e1.printStackTrace();
}
// read
try (FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis)) {
userList = (List<User>) ois.readObject();
} catch (FileNotFoundException | IOException | ClassNotFoundException e1) {
e1.printStackTrace();
}
Notice new FileOutputStream(fileName) does not have the true argument. Using the true argument indicates you want to open the file for "append". Using false, or leaving the append argument off entirely, will open the file for "overwrite".
Notes:
I've also used the try-with-resources statement my example. This eliminates the need for explicitly closing the streams; the streams are automatically closed for you at the end of the try { } block.
I've also used the multi-catch clause, because you are not handling the 3 exceptions any differently, so it is a bit cleaner.

Android ObjectInputStream readObject throws IllegalAccessException

I am trying to write a Serialized Object in my onPause method into a file so that I can read it again from the file when I start the app another time and need the previous data.
This is where i save the Object
try {
FileOutputStream fout = openFileOutput(logFileName, MODE_PRIVATE);
ObjectOutputStream fw = new ObjectOutputStream(fout);
fw.writeObject(obj);
Log.d("obj", "added");
fw.close();
} catch (Exception e) {
Log.d("obj", "not added");
e.printStackTrace();
}
return;
I can see the "added" message and this means that the Object has been saved in the file.
Here is where i try to read the saved object:
try {
FileInputStream fin = openFileInput(logFileName);
ObjectInputStream fread = new ObjectInputStream(fin);
Object res = fread.readObject();
Log.d("obj", "readed successfully");
} catch (Exception e) {
e.printStackTrace();
}
And I get this :
java.io.InvalidClassException: android.view.View; IllegalAccessException
on the line calling "fread.readObject()". I would thank you if you could please tell me why is it throwing the following Exception.
Thanks in Advance.

How to append an object to an existing file (generics)?

I'm having problems with appending a generic object within an existing file. This method is supposed to append the object to the existing file if the parameters are "true" and overwrites the entire file if "false". The "false" statement works perfectly fine, it overwrites the entire file but I can't seem to get the append one to work. It seems to do nothing at first glance but when I placed a simple System.out.println("test"); in the while (true) loop, it runs forever. How can I fix this?
public <T> void writeOneObject(T type, boolean append) throws NotSerializableException{
if (append == true){
//TODO
if (file.exists ()){
ObjectOutputStream ois = null;
try{
ois = new ObjectOutputStream (new FileOutputStream (file, true));
while (true){
ois.writeObject(type);
}
}catch (StreamCorruptedException e){
}catch (EOFException e){
}catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (ois != null) ois.close();
}catch (StreamCorruptedException e){
}catch (IOException e){
e.printStackTrace ();
}
}
}
}
else { //overwrites the entire file
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(type);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (StreamCorruptedException e) {
System.out.println("error");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I also have this inside the class:
class NoHeaderObjectOutputStream extends ObjectOutputStream {
public NoHeaderObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
protected void writeStreamHeader() {}
}

Reading from internal storage (deserialization)

I am using the following method to read from the internal storage:
private void deserialize(ArrayList<Alias>arrayList) {
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
arrayList = (ArrayList<Alias>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
It reads the content of the file "filename" to the "arrayList".
The "serialize" method is as follows:
void serialize(ArrayList<Alias>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that I whenever I run my program again, the "arrayList" is empty. So I guess I am opening the file in wrong input mode.
My aim is to first get the array from the file, then modify it within the app, and then write the modified array back to the file.
Can someone please help me with my problem?
Thanks!
Can you post your pice of your source code? I think the way which you used to parse file content get issue.
Read here:
Android ObjectInputStream docs
I read that the method readObject() read the next object...i this that you must iterate with something like this:
MediaLibrary obj = null;
while ((obj = (MediaLibrary)objIn.readObject()) != null) {
libraryFromDisk.add(obj);
}

how to close the fileInputStream while reading the property file

I have following code :
// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
}catch (IOException e) {
system.out.println("IOEXCeption");
}
Is it required to close the FileInputStream? If yes, how do I do that? I am getting a bad practice error in my code checklist . Asking it to put finally block.
You must the close the FileInputStream, as the Properties instance will not. From the Properties.load() javadoc:
The specified stream remains open after this method returns.
Store the FileInputStream in a separate variable, declared outside of the try and add a finally block that closes the FileInputStream if it was opened:
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream("filename.properties");
properties.load(fis);
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
} catch (IOException e) {
system.out.println("IOEXCeption");
} finally {
if (null != fis)
{
try
{
fis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Use try-with-resources since Java 7:
final Properties properties = new Properties();
try (final FileInputStream fis =
new FileInputStream("filename.properties"))
{
properties.load(fis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOEXCeption: " + e.getMessage());
}
You should always close your streams, and doing it in the finally block is a good practice. The reason for this is that the finally block always gets executed, and you want to make sure that the stream is always closed, even if Something Bad happens.
FileInputStream inStream = null;
try {
inStream = new FileInputStream("filename.properties");
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
} finally {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are using Java 7, this becomes much easier, since a new try-with syntax was introduced. Then you can write like this:
try(FileInputStream inStream = new FileInputStream("filename.properties")){
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
}
and the stream is closed automatically.
here is an example:
public class PropertiesHelper {
public static Properties loadFromFile(String file) throws IOException {
Properties properties = new Properties();
FileInputStream stream = new FileInputStream(file);
try {
properties.load(stream);
} finally {
stream.close();
}
return properties;
}
}
You can use Lombok #Cleanup to do it simply.
http://projectlombok.org/features/Cleanup.html
Properties properties = new Properties();
try {
#Cleanup FileInputStream myFis = new FileInputStream("filename.properties");
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}
Or, only if your are using Java 7, there is the "try with resource" new feature.
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Properties properties = new Properties();
try (FileInputStream myFis = new FileInputStream("filename.properties")) {
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}

Categories