I need to create a copy of an already existing tree , created using DefaultMutableTreeNode.[Edit]
So, I have tried to assign the existing root node, to another DefaultMutableTreeNode.Ex:
DefaultMutableTreeNode ABC = new DefaultMutableTreeNode(null);
DefaultMutableTreeNode ABCcopy = new DefaultMutableTreeNode(null);
ABCcopy=ABC;
But this didnt give me much results.
Please advice.
the easiest way to (deep) copy/clone an object in java is by serializing/deserializing it.
If you use your both trees just for displaying some hierarchical data and do not modify nodes, so the easiest way is this:
JTree new_tree = new JTree(old_tree.getModel());
If you plan to modify one of trees the best way would be to clone.
Here is an example:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream("somefilename");
out = new ObjectOutputStream(fos);
out.writeObject(ABC);
out.close();
} catch(IOException ex) {
ex.printStackTrace();
}
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream("somefilename");
in = new ObjectInputStream(fis);
ABCCopy = (DefaultMutableTreeNode)in.readObject();
in.close();
} catch(IOException ex) {
ex.printStackTrace();
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}
How about
Tree newTree = existingTree.clone() ?
Related
This is my method, he create new object "predmet". class "AddNewObject" return me predmet type (name, description).
AddNewPredmet addnewpredmet = new AddNewPredmet();
listPredmet.add(AddNewPredmet.AddPredmet());
StorageInFile.savePredmet(listPredmet);
All working. But I have a problem with the result written in the file. The output file has symbols that are not readable as shown -
¬н sr java.util.ArrayListxЃТ™Зaќ I sizexp w sr entity.PredmetїБц)Зя| L Descriptiont Ljava/lang/String;L PNameq ~ xpt testt testx
The following is the function that writes to the file
public class StorageInFile {
static void savePredmet(List<Predmet> listPredmet) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("Predmet.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(listPredmet);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Нет такого файла", ex);
} catch (IOException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Не могу записать", ex);
}
}}
How i can fix this? I think about method toString(), but i cant add this method to this code.
Try using a buffered writer and use UTF-8 capable viewer to see the file. You are trying to using a tool that assumes a one-byte encoding, such as the Windows-125x encodings. Notepad is an example of such a tool. So using the capable viewer you can look at it.
Also it would help to show what’s in your file
If you expected to print the contents of every instance of Predmet in the List<> then you could try the following.
Implement to the toString() method in Class Predmet
Try the following snippet to write to file.
FileWriter writer = new FileWriter("sample.txt");
try {
int size = listPredMet.size();
for (int index =0; index < size; index++){
writer.write(listPredMet.get(index).toString());
writer.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
writer.close()
}
Hi im trying to save my ArrayList of objects to a file when onPause() and/or onStop() are called and then have the arrayList read from that file after the app has been killed and relaunched. Ive tried a load of different methods but none seem to work, currently this is what I have.
my code to Write :
try{
FileOutputStream fout = openFileOutput(FILENAME, 0);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(toDos);
oos.close();
}
catch (Exception e){
e.printStackTrace();
}
My code to Read :
try{
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
if(ois.readObject() != null) {
list = (ArrayList<Object>) ois.readObject();
ois.close();
}
}
catch (Exception e){
e.printStackTrace();
}
"FILENAME" is a variable that holds the string "data.txt"
toDos is the name of the arrayList, it is a field at the top of the Activity, it is an ArrayList of object Object which is Serializable.
Not sure what im doing wrong here, and I cant tell if its writing at all or not or where the issue might be.
You are getting an EOFException because you are reading in the object twice; once when you're checking the if statement, and once again inside the if statement. Change your code to something like this:
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
ToDoObject tmp = (ArrayList<ToDoObject>) ois.readObject();
ois.close();
if(tmp != null) {
toDos = tmp;
}
This code accomplishes the same thing but reads from the file a single time.
I started developing an app for my class, which has a request that I need to save objects from a list in a .txt file. It seems to be working, but when I do that, it saves only one object that I entered. I don't know what the solution is. My code is below. P.S. I am using gui to add my objects in a list.
List<Korisnik> listaK=Kontroler.vratiObjekatKontroler().vratiKorisnika();
try {
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
ObjectOutputStream out= new ObjectOutputStream(fos);
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
out.close();
}
You are closing the output stream once you have written the first object. This way you cannot write anything else into it. Move the out.close() out of for loop.
You are closing your stream inside the for loop. I recommend:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(new File("output.txt"));
out= new ObjectOutputStream(fos);
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (out != null) out.close;
if (fos != null) fos.close;
}
Hoping that you are using at least Java SE 7 :) you can take advantage of try-with-resources so you don't need to care about closing "resources":
try (
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
ObjectOutputStream out= new ObjectOutputStream(fos)
){
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
}
The try-with-resources statement contains the FileOutputStream and ObjectOutputStream object declarations that are separated by a semicolon. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the FileOutputStream and ObjectOutputStream objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.
In my Android application I'm trying to store a Map structure such as:Map<String, Map<String, String>>using internal storage. I've looked into using SharedPreferences, but as you know, this only works when storing primitive data types. I tried to use FileOutputStream, but it only lets me write in bytes...Would I need to somehow serialize the Hashmap and then write to file?
I've tried reading through http://developer.android.com/guide/topics/data/data-storage.html#filesInternal but I can't seem to find my solution.
Here's an example of what I'm trying to do:
private void storeEventParametersInternal(Context context, String eventId, Map<String, String> eventDetails){
Map<String,Map<String,String>> eventStorage = new HashMap<String,Map<String,String>>();
Map<String, String> eventData = new HashMap<String, String>();
String REQUEST_ID_KEY = randomString(16);
. //eventData.put...
. //eventData.put...
eventStorage.put(REQUEST_ID_KEY, eventData);
FileOutputStream fos = context.openFileOutput(EVENT_FILENAME, Context.MODE_PRIVATE);
fos.write(eventStorage) //This is wrong but I need to write to file for later access..
}
What is the best approach for storing this type of a data structure internally in an Android App? Sorry if this seems like a dumb question, I am very new to Android. Thanks in advance.
HashMap is serializable, so you could just use a FileInputStream and FileOutputStream in conjunction with ObjectInputStream and ObjectOutputStream.
To write your HashMap to a file:
FileOutputStream fileOutputStream = new FileOutputStream("myMap.whateverExtension");
ObjectOutputStream objectOutputStream= new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(myHashMap);
objectOutputStream.close();
To read the HashMap from a file:
FileInputStream fileInputStream = new FileInputStream("myMap.whateverExtension");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map myNewlyReadInMap = (HashMap) objectInputStream.readObject();
objectInputStream.close();
+1 for Steve P's answer but it does not work directly and while reading I get a FileNotFoundException, I tried this and it works well.
To Write,
try
{
FileOutputStream fos = context.openFileOutput("YourInfomration.ser", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myHashMap);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
And to Read
try
{
FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"/FenceInformation.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map myHashMap = (Map)objectInputStream.readObject();
}
catch(ClassNotFoundException | IOException | ClassCastException e) {
e.printStackTrace();
}
Writing:
FileOutputStream fos = context.openFileOutput(EVENT_FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream s = new ObjectOutputStream(fos);
s.writeObject(eventStorage);
s.close();
Reading is done in the inverse way and casting to your type in readObject
I am trying to add serilization and deserialization to my app. I have already added serization which makes it into a textfileThis problem is involving ArrayLists. I was browsing this page: http://www.vogella.com/articles/JavaSerialization/article.html when I saw this code:
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (Person) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
I was confused on this line:
p = (Person) in.readObject();
How do I make this line an ArrayList when creating an ArrayList is not as simple as that:
List<String> List = new ArrayList<String>();
Thanks for the help in advance!
I took the code directly from the website that you provided a link for and modified it for an ArrayList. You mention "How do I make this line an ArrayList when creating an ArrayList is not as simple as that", I say creating an ArrayList is as simple as that.
public static void main(String[] args) {
String filename = "c:\\time.ser";
ArrayList<String> p = new ArrayList<String>();
p.add("String1");
p.add("String2");
// Save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(p);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// Read the object from file
// Save the object to file
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (ArrayList<String>) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
prints out [String1, String2]
Have you written a whole ArrayList as an object in the file?
Or have you written Persons object that were in an ArrayList in a loop in the file?