saving an array to a serialised file
Hello,
I'm trying to save an array as a serialisable object to a file. Content from a textField will be added to the array from a button.
I have a class Save.java with code:
import java.io.*;
import java.util.*;
public class Save implements Serializable {
/** Creates a new instance of Save */
public Save() {
List save = new ArrayList();
ObjectOutputStream oos = null;
try
{
oos = new ObjectOutputStream(new FileOutputStream("filename.ser")); //need .ser as the file type!!
}
catch (IOException i)
{
System.out.println( "Error opening file");
}
try
{
oos.writeObject(save); //the object you want saving goes in the brackets.
}
catch (IOException o)
{
System.out.println("Error writing file");
}
try
{
if(oos != null)
oos.close();
}
catch (IOException x)
{
System.out.println("Error closing file");
}
}
}
And in the main class i have:
import java.io.*;
import java.util.*;
public class main extends javax.swing.JFrame {
/**
* Creates new form main
*/
public main() {
initComponents();
}
.....
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
save.add(jTextField3);
Save();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
}
});
}
--
I'm having trouble linking the Save.java class to the main class and adding content from a textfield to the arary for saving to the file.
Any ideas?
Sorry if i've explained myself awfully lol.
I've been seeing this in a number of code examples posted to these forums:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
What's going on here? That looks like the actionPerformed method of ActionListener, but I don't see ActionListener being implemented anywhere?
it is there.. its in the netbeans generated code section. I didnt want to copy it all since i have a rather large GUI setup.
> I've been seeing this in a number of code examples
> posted to these forums:
> > private void
> jButton2ActionPerformed(java.awt.event.ActionEvent
> evt)
>
> What's going on here? That looks like the
> actionPerformed method of ActionListener, but I don't
> see ActionListener being implemented anywhere?
IDE code generation. I think it then usually adds an anonymous listener:
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
jButton2ActionPerformed(evt);
}
});
> IDE code generation. I think it then usually adds an anonymous listener:What's the point to having this extra indirection? Is it good design?At least the code didn't invoke reflection to search for the method based on a component's name :-)
yep :)
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
> > IDE code generation. I think it then usually adds
> an anonymous listener:
>
> What's the point to having this extra indirection? Is
> it good design?
No idea. I'd say it's bad design. I think I've seen it in JBuilder. I hated JBuilder's IDE code generation. So hard to read it. Especially because it didn't keep all initialization of a component together--no logic whatsoever (as far as I could tell) as to the order of initializing things.
> At least the code didn't invoke reflection to search
> for the method based on a component's name :-)
Blech! :-)
And why not import the classes, instead of spelling out the fully qualified name?
Create a "Save" instance in your "main" class:
private Save save = new Save();
Then in your actionPerformed, you can call:
save.add(jTextField3.getText());
In Save, you need to make the ArrayList a private instance variable (call it saveList), and then write a method:
public void add(String value)
{
saveList.add(value);
}
Then, somewhere, you'll need a button whose actionPerformed says:
save.saveToFile();
where you'll need a saveToFile method in Save.
I don't think you want Save to implement Serializable--you are serializing an ArrayList, not a Save object.
By the way, you need to rename your JButtons and JTextFields now. Your code will be easier for you and others to read if the variable names are meaningful.
thanks alot, works nicely :)
>I don't think you want Save to implement Serializable--you are serializing an ArrayList, not a Save object.
How would i serialize the array and not the Save Object? I've never really touched upon serializing until very recently :S so it's a bit confusing.
By the way, say if i wanted the contents of multiple texboxes stored into an array (for instance, item: lightbulbs etc, quantyity: 5 etc) which was then stored inside another array (say, "required materials", which stored all the required items for a specific task) How would i go about developing my current code structure to enable this?
> thanks alot, works nicely :)
You're welcome. I realized after arguing about the strange code generation, we hadn't addressed your real question. :)
> >I don't think you want Save to implement
> Serializable--you are serializing an ArrayList, not a
> Save object.
>
> How would i serialize the array and not the Save
> Object? I've never really touched upon serializing
> until very recently :S so it's a bit confusing.
You are already serializing just the ArrayList. You passed the list to writeObject, not the whole Save object.
> By the way, say if i wanted the contents of multiple
> texboxes stored into an array (for instance, item:
> lightbulbs etc, quantyity: 5 etc) which was then
> stored inside another array (say, "required
> materials", which stored all the required items for a
> specific task) How would i go about developing my
> current code structure to enable this?
You could make a very simple Item class with a name (String) and quantity (int). You'd read from each textfield and create an Item object, and add that to the ArrayList.
>You're welcome. I realized after arguing about the strange code generation, we hadn't addressed your real question. :)
lol it's np :)
>You could make a very simple Item class with a name (String) and quantity (int). You'd read from each textfield and create an Item object, and add that to the ArrayList.
So i'd have a really simple class:
public class item {
/** Creates a new instance of Ingredients */
public Ingredients() {
String name;
int quantity;
}
}
and in the main, on a button actionlistener i'd create a new instance of item:
private Item item = new Item();
and assign 2 textfields to the variables name and quantity?
item.name(name.getText());
item.quantity(quantity.getText());
So in the end i could essentially have job[1](requiredMaterials[1](name, quantity)...
job[1](requiredMaterials[2](name,quantity) <-- which would hold the second Item details inside the required materials section for a specific job?
Thank you super much for your help :)
> So i'd have a really simple class:
>
> public class item {
>
> /** Creates a new instance of Ingredients */
>public Ingredients() {
>String name;
>int quantity;
> }
>}
>
Close. You'd need to have the name and quantity defined outside the constructor:
public class item {
/** Creates a new instance of Ingredients */
public Ingredients() {}
String name;
int quantity;
}
You could make a constructor that takes a name and quantity, and you could make getters and setters. For something very simple, you might not need that.
> and in the main, on a button actionlistener i'd
> create a new instance of item:
>
> private Item item = new Item();
Yes, but you can't have the word "private".
> and assign 2 textfields to the variables name and
> quantity?
>
> item.name(name.getText());
> item.quantity(quantity.getText());
Yes.
> So in the end i could essentially have
> job[1](requiredMaterials[1](name, quantity)...
> job[1](requiredMaterials[2](name,quantity) <-- which
> would hold the second Item details inside the
> required materials section for a specific job?
Yes, you could have a Job class that contains an ArrayList called requiredMaterials. The ArrayList would contain Items. Then you could have multiple Job instances, each with its own list of requiredMaterials.
> Thank you super much for your help :)
You're welcome.
One small question.
private void addItemActionPerformed(java.awt.event.ActionEvent evt) {
Item item = new Itemt();
item.name(itemName.getText());
// get an error Cannot find symbol: method name
item.quantity(quantity.getText());
// get an error Cannot find symbol: method name
}
public class Item {
/** Creates a new instance of Item */
public Item() {}
String name;
int quantity;
String unit;
}
what am i doing wrong?
Message was edited by:
KingScooty
It looks like you don't have your classes in a package. The variables in Item are package-private (since you didn't specify otherwise), so your other code can't access it.
Before String and int in Item, put the word "public". For example:
public String name;
hmm, i still get the same errors.
main.java:211: cannot find symbol
symbol : method name(java.lang.String)
location: class submission2.Item
item.name(itemName.getText());
main.java:212: cannot find symbol
symbol : method quantity(java.lang.String)
location: class submission2.Item
item.quantity(quantity.getText());
2 errors
BUILD FAILED (total time: 0 seconds)"
I noticed for the array/save class i have:
public void add(String value)
{
recipeList.add(value);
}
and in the main i have:
Save.add(jTextfield3.getText());
should i do something similar for the item class?
Oh, sorry. I wasn't even thinking. You did need to make them public (probably). But, you also need to assign variables--not call methods:
item.name = itemName.getText();
// Quantity is an int, not a String
item.quantity = Integer.parseInt(quantity.getText());
You could make a "setName":
item.setName(itemName.getText());
But, you can assign the variables directly if they are public (not usually best to make them public, but for something simple like this, it might be okay for now).
>item.name = itemName.getText();>// Quantity is an int, not a String>item.quantity = Integer.parseInt(quantity.getText()); Ahh!! Makes sense! Works perfect now! :) Thank you so much!