Retrieving image icon for the objects saved after deserialization - java

-The array of appliances(clock,lamp or television) is displayed on an array of labels (pictures[]) in a 3x3 grid
-An example of outputting an appliance icon (which is when a device is added to the grid though a button labelled 'add device')
Television myTelevision = new Television();
appliance[count-1] = myTelevision;
pictures[count-1].setIcon(appliance[count-1].getPicture());
This is my code for saving the array of appliances (objects) to a file and reading them back in ( re-populating the appliance array):
if(e.getSource()==but3)
{
ObjectInputStream input
= null;
try {
input = new ObjectInputStream(
new FileInputStream("livingroom.bat"));
Appliance[] appliance = (Appliance[]) (input.readObject());
} catch (IOException ex) {
Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex)
{
Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
input.close();
} catch (IOException ex) {
Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if(e.getSource()==but4)
{
ObjectOutputStream output
= null;
try {
output = new ObjectOutputStream(
new FileOutputStream("livingroom.bat", true));
output.writeObject(appliance);
} catch (IOException ex) {
Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
output.close();
} catch (IOException ex) {
Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
After deserialization I am trying to display the imageicon for the appliances in the array (which has just been re-populated). However no matter how I try nothing seems to happen (the grid of pictures shows no change).
What I am asking for: Can anyone tell me a method of applying the image icons for the appliances to the grid of pictures once deserialization has taken place?

You are deserialising into a local variable whose scope ends with the try block it is declared in, and you don't do anything with the local variable, so nothing happens.
Presumably you should be deserialing into a member variable.

Related

Workaround java.io.EOFException cause by ObjectInputStream [duplicate]

This question already has answers here:
java.io.FileNotFoundException when creating FileInputStream
(2 answers)
Closed 6 years ago.
For my application I want to use a Map to act as a database. To save and load a map, I am writing/reading it to/from database.ser using this 2 methods:
private synchronized void saveDB() {
try {
fileOut = new FileOutputStream(db);
out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
fileOut.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to load into Map when application starts, so I invoke method in constructor like this:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("C:/Users/eduar/git/Multy-Threaded-Bank-System/Bank-Services/database.ser");
// also, any suggestions how can I make path to a file more flexible in case I want to run Server side of an app on different machine?
if (!db.exists()) {
try {
db.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
loadDB(); // loads database when server start
}
I am aware of what causing an error, but I don't know what should I change in my design to avoid ObjectInputStream constructor receiving empty stream!
Any suggestions on what I can do differently?
Edit: I want to note that in fresh application run database.ser is empty since there was no entries made into Map yet.
Thank You!
First why the EOFExcpetion occur?
There are no contents in file or file is empty and you tried to read file.
You can avoid the EOFException for an empty file by checking file content length if it is less than or equal to zero means file is empty. another way to check if file is empty
Some code change and it worked for me.
#SuppressWarnings("unchecked")
private void loadDB() {
try {
if (db.length() <= 0) {
// if statement evaluates to true even if file doesn't exists
saveDB(); // save to a file an empty map
// if file doesn't exist, it creates a new one
// call loadDB inside constructor
}
FileInputStream fileIn = new FileInputStream(db);
ObjectInputStream in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
in.readObject();
in.close();
fileIn.close();
System.out.println(accounts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Get rid of the file.exists()/file.createNewFile() crap. All it is doing for you is masking the original FileNotFoundException problem, and turning into a thoroughly predictable EOFException because of trying to construct an ObjectInputStream around an empty stream. Handle the original problem. Don't just move it, or turn it into something else.

new jframe appears behind current jframe

I'm with some trouble here
I did a main CRUD form, and one button at this form that when clicked it calls another form, this one responsible for makes a query at the database to order the dates and hours that were entered by the user and display at the screen... but here is the deal, when I click at the button "Listar Por Prioridade" to call this form "Trabalhos Prontos" it appears behind the first one "Registro de Novos Chamados"... I've tried to use:
private void btListarPrioridadeActionPerformed(java.awt.event.ActionEvent evt) {
try {
man = new MySQLDaoManager("root", "", "localhost", "atendimentos", 3306);
try {
FormTrabProntos frmTrbPrnt = new FormTrabProntos(man);
frmTrbPrnt.setVisible(true);
frmTrbPrnt.toFront();
FormNovaChamada frmNvCham = new FormNovaChamada(frmini, editavel);
frmNvCham.toBack();
} catch (DAOException ex) {
Logger.getLogger(FormGestor.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(FormGestor.class.getName()).log(Level.SEVERE, null, ex);
}
}
and nothing (see image below).. anyone knows how could I fix this problem and make the called screen appears at the front of the first one?! Thanks a lot
Finally i've solved it, the function stayed as follows:
private void btPriorityListActionPerformed(java.awt.event.ActionEvent evt) {
try {
man = new MySQLDaoManager("root", "", "localhost", "attendances", 3306);
try {
setVisible(false);
dispose();
FormTrabProntos frmTrbPrnt = new FormTrabProntos(man);
frmTrbPrnt.setVisible(true);
frmTrbPrnt.toFront();
frmTrbPrnt.requestFocus();
} catch (DAOException ex) {
Logger.getLogger(FormGestor.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(FormGestor.class.getName()).log(Level.SEVERE, null, ex);
}
}
Big thanks for the help!!!

Java Serialization not working, appears broken because of IDE

EDIT: The error was caused by Netbeans not the code. Post has been edited to show all the code since the Git files are being removed.
I have a group project at school to design a tower defense game and I have been attempting to add Serialization.
Here is the code:
public class Serialization implements Serializable {
private static FileOutputStream file;
private static ObjectOutputStream write;
public static boolean checkFile(String name){
boolean check = false;
check = new File("log",name+".ser").isFile();
return check;
}
public static void createFile(String name) {
try {
file = new FileOutputStream("log/"+name+".ser");
} catch (FileNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ObjectOutputStream openFile(String name) {
try {
file = new FileOutputStream("log/"+name+".ser");
write = new ObjectOutputStream(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
return write;
}
public static void addLine(ObjectOutputStream con,Object data) {
try {
con.writeObject(data);
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void readLine(String name){
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream("log/"+name+".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.readObject());
in.close();
fileIn.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileIn.close();
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void closeFile(ObjectOutputStream con){
try {
con.close();
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I eventually abandoned it for two reasons. One it was overkill (trying to have a central class that handles multiple serialization files) and two I could not get it to work with what I am about to talk about.
What I really wanted was to serialize the enemyArray. This holds every living enemy in the game and all their information (stats). If you scroll down to line 192 that is what is left of my serialization attempts:
public void serialize(){
if (Serialization.checkFile("test")==false){
Serialization.createFile("test");
}
ObjectOutputStream connection = Serialization.openFile("test");
for (int x=0;x<enemyArray.length;x++){
if (enemyArray[x]!=null){
Serialization.addLine(connection,enemyArray[x]);
}
}
//Serialization.addLine(connection,enemyArray);
Serialization.closeFile(connection);
enemyArray = null;
Serialization.readLine("test");
//System.out.println(enemyArray[0].id);
// try {
// FileOutputStream fileOut = new FileOutputStream("log/test.ser");
// ObjectOutputStream out = new ObjectOutputStream(fileOut);
// out.writeObject(enemyArray);
// out.writeUTF(t);
// // Do work here
// for (int x=0;x<enemyArray.length;x++){
// if (enemyArray[x]!=null){
// Enemy tmp = enemyArray[x];
// System.out.println(tmp+" >>> "+enemyArray[x]);
// out.writeObject(tmp);
// }
// }
// out.close();
// fileOut.close();
// } catch (FileNotFoundException ex) {
// Logger.getLogger(EnemyController.class.getName()).log(Level.SEVERE, null, ex);
// } catch (IOException ex) {
// Logger.getLogger(EnemyController.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
It will create the file but will not save anything to it. What is wrong with the code? from what I studied enemyArray shouldn't be static so I removed that and still no change.
Try doing a out.flush(); brefore you close thre output stream.
I found the error after some troubleshooting in the computer lab with my group. Hopefully this can help anyone who finds themselves in my situation or in a similar Java file read/ write issue.
My IDE, Netbeans, shows the file in the files and project list once it is dynamically created, but because it was filled with serialized data and was created after the project was opened and run it would only display an empty file when in reality there is actually data inside the file. String data is fine so it may only be certain data types (like serialized objects) that trigger this error.
Several different versions of my code were correct but they all seemed broken because an empty file was returned to the IDE. The solution is two fold:
Manually check it through your file explorer. It will show a size and can be opened in another editor but may still be buggy in the IDE you ran the program in.
Close down your IDE and on reopening, at least in Netbeans case, the file should be updated correctly.
On a similar note Netbeans may just all together keep showing the empty file instead of offering you the option to select the files encoding. Just view the file in your explorer in this case and if the size is greater than 0 you know your code is ok. This is purely an IDE error.

Java all values null when deserializing an array list

I'm making a java program as a challenge to myself to learn, and I'm currently having trouble with serializing and de-serializing an arraylist. When I de-serialize all of the values are null.
This is the function that initially serializes the list:
private void saveModList(ArrayList<Moderator> m) {
try {
ObjectOutputStream fOut = new ObjectOutputStream(new FileOutputStream("data/modlist.ctm"));
fOut.writeObject(m);
fOut.close();
} catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Could not save moderator list.",
"Save error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
This is the function that deserializes the list:
public static ArrayList<Moderator> openModList() {
try {
ObjectInputStream fIn = new ObjectInputStream(new FileInputStream("data/modlist.ctm"));
try {
return (ArrayList<Moderator>) fIn.readObject();
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Could not open moderator list",
"Read error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
fIn.close();
} catch(FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Could not load moderator data. File not found.",
"Moderator file not found.", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} catch(EOFException ex) {
} catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Could not load moderator data.",
"Error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
//If something screws up, return null, and the user will not be logged in
return null;
}
And this calls the function to deserialize
ArrayList<Moderator> modLoginList = new ArrayList<Moderator>();
modLoginList = Main.openModList();
//Check all of the moderators.
//If one of them matches up to a moderator username and password, log them in
for(int i = 0; i < modLoginList.size(); i++) {
if(modLoginList.get(i).name.equals(username) && modLoginList.get(i).password.equals(password)) {
loggedIn = true;
break;
}
}
When I do this, I also get a NullPointerException at the if statement, checking if the moderator's credentials are valid. When I go and just try and print out the values outright, they are null. The moderator class does implement serializable and has a serial version ID. Any suggestions on why this is happening and how to fix it/better ways to do this are greatly appreciated.
Also it is not just returning null outright because there was nothing to read, or something went wrong.
The NullPointerException appears to come from the openModList method returning null. One option is to surround your for loop with a null check:
if (modLoginList != null) {
for(int i = 0; i < modLoginList.size(); i++) {
if(modLoginList.get(i).name.equals(username) && modLoginList.get(i).password.equals(password)) {
loggedIn = true;
break;
}
}
}
It's possible that the object reference you're serializing is null. So check the part of your code that adds objects to the ArrayList before passing it for serialization.
That said, your code could use other changes, such as instead of this block:
try {
return (ArrayList<Moderator>) fIn.readObject();
} catch (ClassNotFoundException ex) {
...
ex.printStackTrace();
}
fIn.close();
add a finally clause:
try {
return (ArrayList<Moderator>) fIn.readObject();
} catch (ClassNotFoundException ex) {
...
ex.printStackTrace();
} finally {
fIn.close();
}
The finally clause will be executed regardless of what happens with the try/catch clauses.

Saving a singleton object

I know this site isn't made for questions like this but I've been searching for the answer to this I haven't found anything and I need a confirmations.
I have a singleton class which is the centre of my program, in some situations I try to save its state, however it seems it doesn't save properly, and I don't see why because It's not the first time I do this, however It is the first time I try to save a singleton, so is it possible to save a singleton object?
Here are my loading and saving codes of this object
public void Loading(String name) {
ObjectInputStream is = null;
//ignore this variable
game_loaded = 1;
try {
is = new ObjectInputStream(new FileInputStream(name + ".dat"));
//Logica is the singleton class,
//logi is the name of the variable where it is
logi = (Logica) is.readObject();
} catch (FileNotFoundException e1) {
JOptionPane.showOptionDialog(frame, "Game Invalid", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
return;
} catch (IOException e1) {
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
JOptionPane.showOptionDialog(frame, "Game Loaded Sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
}
Save:
public void saving(String nome){
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(nome+".dat"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
try {
os.writeObject(Logica.getLogica(null));
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
JOptionPane.showOptionDialog(frame, "Game Saved sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
if (os != null)
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT
Ok I may have explained corretcly, it doesn't give me any error loading, however it doesn't load the state I saved, it loads an new "Logica" as if I had created a new one
There's nothing about Singleton per se that says it can't be serialized; you can write incorrect serialization code for any class. It's not clear what's wrong, and I'm not willing to pore over your code to figure it out, but it should be possible to do.
You have an empty catch block for IOException. That's always a bad idea. You've swallowed the exception that might explain everything. Print the stack trace.
The situation you have described is not possible. Ergo you haven't described it correctly. Probably there is something wrong with your observations.
I strongly suspect an IOException or FileNotFoundException, despite your comment in another answer. You have posted code that ignores exceptions in at least four separate places. The presumption is overwhelming.
In fact your exception handling needs a lot of work. You aren't closing the file in case of exceptions for example. There are no finally blocks. You have multiple try/catch blocks where you should have one try and several catches.
Further questions along other lines of enquiry. Is the file being created? With non-zero length? Or else maybe the singleton class only has transient fields?

Categories