I have a Hashtable<String, String>table contains data to be stored in a text file , I stored it as an Object like this way:
Hashtable<String, String>table1=new Hashtable<String,String>();
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(table1);
oos.close();
fos.close();
Then I tried to read it like an Object as I had stored it like this way:
Hashtable<String, String>table2=new Hashtable<String,String>();
FileInputStream reader=new FileInputStream(file);;
ObjectInputStream buffer=new ObjectInputStream(reader);
Object obj=buffer.readObject();
table2=(Hashtable<String, String>)obj;
buffer.close();
reader.close();
but the problem is table2 still null !! I think the problem is in the way of reading, please any useful way of reading ?
I suggest you use a HashMap<String, String> instead of Hashtable<String, String> and program to the Map<String,String> interface, I would also suggest you use try-with-resources, finally make sure to store something in your Collection before you serialize it.
File f = new File(System.getProperty("user.home"), "test.ser");
Map<String, String> table1 = new HashMap<>();
table1.put("Hello", "world");
try (FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(table1);
} catch (Exception e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);) {
Map<String, String> table = (Map<String, String>) ois.readObject();
System.out.println(table);
} catch (Exception e) {
e.printStackTrace();
}
Output is
{Hello=world}
Related
For a college project i have to save a hashmap of Lists to a binary file. Then i have to be able to load it again but im having a bit of trouble. It will save my file but will not load it. Here is my code:
This is Saving:
private static void storeRec()
{
try
{
File f = new File("recommendation.dat");
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(localStore);
oos.flush();
oos.close();
fos.close();
System.out.println("Recommendation read to File");
}
catch (IOException ex)
{
Logger.getLogger(Project2.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is the loading code :
List<Recommendation> newmovies = new ArrayList<>();
try
{
File f = new File("recommendation.dat");
if(f.exists())
{
DataInputStream dis = new DataInputStream(new FileInputStream(f));
/*FileInputStream streamIn = new FileInputStream(f);
ObjectInputStream dis = new ObjectInputStream(streamIn);*/
while(dis.available()>0)
{
byte[] titleBytes = new byte[32];
dis.read(titleBytes);
String title = new String(titleBytes);
byte[] queryBytes = new byte[32];
dis.read(queryBytes);
String query = new String(queryBytes);
byte[] directorBytes = new byte[32];
dis.read(directorBytes);
String director = new String(directorBytes);
byte[] summaryBytes = new byte[64];
dis.read(summaryBytes);
String summary = new String(summaryBytes);
byte[] categoryBytes = new byte[18];
dis.read(categoryBytes);
String category = new String(categoryBytes);
//String category = dis.readUTF();
double rating = dis.readDouble();
int release = dis.readInt();
byte[] castBytes = new byte[64];
dis.read(castBytes);
String cast= new String(castBytes);
ArrayList<String> castArrayList = new ArrayList<>(Arrays.asList(cast.split(",")));
int myRating = dis.readInt();
byte[] commentsBytes = new byte[32];
dis.read(commentsBytes);
String myComments = new String(commentsBytes);
newmovies.add(new Recommendation(title,query,director,summary,release,category,rating,castArrayList,myRating,myComments));
//System.out.println(newmovies);
localStore.put(query, newmovies);
}
}
LocalStore is a hashmap i would like to add the data from the file to. The key is the Query. For some reason it will not add to the map
Any help would be very much appreciated.
You have to use an ObjectInputStream on a file created by ObjectOutputStream, and readObject()to read an object written by writeObject().
And available() is not a valid test for end of stream. See the Javadoc. You have to catch EOFException.
I'm trying to read a map of Students from a txt file, after that I add a new student to the map (now is bigger than before) and save it back to the file. After I close my program and reload the data from file, the new students weren't saved.
HashMap<String, Student> studentObj = new HashMap<>(SIZE);
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME));
studentObj = (HashMap<String, Student>) in.readObject();
studentObj.put(student.getStudentID(), student);
ObjectOutputStream out;
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(DEFAULT_FILE_NAME)));
out.writeObject(studentObj);
out.flush();
System.out.println("here " + studentObj.size());
in.close();
out.close();
} catch (IOException e) {
throw new Exception("FILE IS NOT CREATED");
} catch (ClassNotFoundException e) {
throw new Exception("CLASS NOT FOUND EXCPETION");
}
I agree with #xdevs23
Instead of saving the data into arrays (which will use more memory), you could write
/*import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;*/
HashMap<String, Student> studentObj = new HashMap<>(SIZE);
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME));
studentObj = (HashMap<String, Student>) in.readObject();
studentObj.put(student.getStudentID(), student);
in.close();
System.out.println("here " + studentObj.size());
FileOutputStream fos = new FileOutputStream(DEFAULT_FILE_NAME);
OutputStreamWriter osw = new OutputStreamWriter(fos);
Writer w = new BufferedWriter(osw);
// Iterate using YOUR hash keys
for(int i = 0; i < studentObj.size(); i++){
w.write(studentObj.get(i).getString());
w.write(studentObj.get(i).getStudent());
}
w.close();
catch (IOException e) {
throw new Exception("FILE IS NOT CREATED");
} catch (ClassNotFoundException e) {
throw new Exception("CLASS NOT FOUND EXCPETION");
}
}
And just write the data pulled from ObjectInputStream directly to the file
My code was ok. The problem was that after saving the object to the file, then I closed the app and opened it again. Then, the constructor created a new file that overrides the old one. I added an if statement to create the file just for the first time. I used txt to make it simple and fast because is just a small task. I love to use xml files instead :) And yes, JAVA can save objects.
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?
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() ?