How to save Hashset to file in Android? - java

I'm trying to export a Hashset (integer) to file with the following code but it appears I can't use outputStream.write() to do it. There don't seem to be any previous questions here or on google that cover it which surprises me.
Hashset is defined in the Activity as:
HashSet<Integer> set = new HashSet<Integer>();
and Method is:
public void savehashset(){
String filename="storedhashset.set";
File storedhashset = new File(getFilesDir(), filename);
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(set);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

You are trying to serialize your HashSet on a file. For this purpose you can use an ObjectOutputStream
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(set);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
From the doc of writeObject:
Writes an object to the target stream.

Since HashSet implements Serializable, you can try this:
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("object.data"));
HashSet<Integer> object = new HashSet<Integer>();
output.writeObject(object);
//etc.
output.close();

Related

updating ini file in java using rest webservice

I need to update ini file in java using rest service.I could read file in browser but have no idea how to update it.Can anybody please help for the required method that would update my ini file.
dbform.java
public class dbform {
public List<db> getAlldb(){
List<db> dbList = null;
try {
File file = new File("test.ini"); // read ini file
if (!file.exists()) {
db DB = new db("dbname: test","password: test");
dbList = new ArrayList<db>();
dbList.add(DB);
savedbList(dbList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
dbList = (List<db>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return dbList;
}
private void savedbList(List<db> dbList){
try {
File file = new File("test.ini");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dbList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try to use ini4j.
The [ini4j] is a simple Java API for handling configuration files in Windows .ini format. Additionally, the library includes Java Preferences API implementation based on the .ini file.
http://ini4j.sourceforge.net/
Check your code there seems to be some issue in the way you have called the function. You don't seem to be passing the dbList into the replaceData() function. Probably it will be something like this
public void replaceData(List<db> dbList){ return DBform.savedbList(dbList); }

Saving Class Type info to file for later use

As you know, passing class types is important when programming Android applications.
One simple example is using an Intent.
Intent i = new Intent(this, MyActivity.class);
So it'll be kind of useful in some situations if I can save the class type info to a file for later use, for instance, after reboot.
void saveClassTypeInfo(Class<?> classType, String filename) {
String str = null;
// Some job with classType
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
fos.write(str.getBytes());
fos.close();
} catch (Exception e) {
}
}
If I could save in a certain way like above, then I would be able to put it back to an Intent like this in the future.
Intent i = new Intent(this, restoredClassInfoFromFile);
How I can achieve this kind of job? Because Class<?> is not an object, I don't know where to start at all.
[EDIT]
.class is an object too, so we can save it just like saving an object.
This is possible using ObjectOutputStream here SaveState is your Custom class
public static void saveData(SaveState instance){
ObjectOutput out;
try {
File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.ser");
out = new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(instance);
out.close();
} catch (Exception e) {e.printStackTrace();}
}
public static SaveState loadData(){
ObjectInput in;
SaveState ss=null;
try {
in = new ObjectInputStream(new FileInputStream("appSaveState.ser"));
ss=(SaveState) in.readObject();
in.close();
} catch (Exception e) {e.printStackTrace();}
return ss;
}
Full Tutorial write to File available here
And Read Object from File here

cannot find symbol on .readObject();

I'm having trouble loading my save file and its showing me a "cannot find symbol" error in the .readObject() of the 2 int variables. I properly declared the variables and both variables are global. I have no idea why. I tried searching for an answer so i end up here. ty in advance guys
public void loadGame()
{
//Load Game
try
{
FileOutputStream saveFile = new FileOutputStream("save.txt");
ObjectOutputStream load = new ObjectOutputStream(saveFile);
cursortrigger = (Integer) load.readObject();
soundtrigger = (Integer) load.readObject();
load.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void saveGame()
{
//Save Game
try
{
FileOutputStream saveFile = new FileOutputStream("save.txt");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(cursortrigger);
save.writeObject(soundtrigger);
save.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
FileOutputStream saveFile = new FileOutputStream("save.txt");
ObjectOutputStream load = new ObjectOutputStream(saveFile);
This is wrong. To read objects, you need ObjectInputStream and FileInputStream.
FileInputStream saveFile = new FileInputStream("save.txt");
ObjectInputStream load = new ObjectInputStream(saveFile);
You need ObjectInputStream, not ObjectOutputStream. Also FileInputStream.

How to write and read java serialized objects into a file

I am going to write multiple objects to a file and then retrieve them in another part of my code. My code has no error, but it is not working properly. Could you please help me find what is wrong about my code.
I read different codes from different websites, but none of them worked for me!
Here is my code to write my objects to a file:
MyClassList is an arraylist which includes objects of my class (which must be written to a file).
for (int cnt = 0; cnt < MyClassList.size(); cnt++) {
FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList.get(cnt));
}
I added "true" to the constructor of the outputstream, because I want to add each object to end of the file. Is that correct?
And here is my code to read the objects from the file:
try {
streamIn = new FileInputStream("G:\\address.ser");
ObjectInputStream objectinputstream = new ObjectInputStream(streamIn);
MyClass readCase = (MyClass) objectinputstream.readObject();
recordList.add(readCase);
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
}
It finally prints out just one object. Now, I don't know if I am not writing correctly or reading correctly!
Why not serialize the whole list at once?
FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);
Assuming, of course, that MyClassList is an ArrayList or LinkedList, or another Serializable collection.
In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.
As others suggested, you can serialize and deserialize the whole list at once, which is simpler and seems to comply perfectly with what you intend to do.
In that case the serialization code becomes
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
fout = new FileOutputStream("G:\\address.ser", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(myClassList);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(oos != null){
oos.close();
}
}
And deserialization becomes (assuming that myClassList is a list and hoping you will use generics):
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream("G:\\address.ser");
objectinputstream = new ObjectInputStream(streamIn);
List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
recordList.add(readCase);
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
objectinputstream .close();
}
}
You can also deserialize several objects from a file, as you intended to:
ObjectInputStream objectinputstream = null;
try {
streamIn = new FileInputStream("G:\\address.ser");
objectinputstream = new ObjectInputStream(streamIn);
MyClass readCase = null;
do {
readCase = (MyClass) objectinputstream.readObject();
if(readCase != null){
recordList.add(readCase);
}
} while (readCase != null)
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
objectinputstream .close();
}
}
Please do not forget to close stream objects in a finally clause (note: it can throw exception).
EDIT
As suggested in the comments, it should be preferable to use try with resources and the code should get quite simpler.
Here is the list serialization :
try(
FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
){
oos.writeObject(myClassList);
} catch (Exception ex) {
ex.printStackTrace();
}
Simple program to write objects to file and read objects from file.
package program;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class TempList {
public static void main(String[] args) throws Exception {
Counter counter = new Counter(10);
File f = new File("MyFile.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(counter);
oos.close();
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Counter newCounter = (Counter) ois.readObject();
System.out.println(newCounter.count);
ois.close();
}
}
class Counter implements Serializable {
private static final long serialVersionUID = -628789568975888036 L;
int count;
Counter(int count) {
this.count = count;
}
}
After running the program the output in your console window will be 10 and you can find the file inside Test folder by clicking on the icon show in below image.
I think you have to write each object to an own File or you have to split the one when reading it.
You may also try to serialize your list and retrieve that when deserializing.
if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.
Serialization:
LinkedList<YourObject> listOfObjects = <something>;
try {
FileOutputStream file = new FileOutputStream(<filePath>);
ObjectOutputStream writer = new ObjectOutputStream(file);
for (YourObject obj : listOfObjects) {
writer.writeObject(obj);
}
writer.close();
file.close();
} catch (Exception ex) {
System.err.println("failed to write " + filePath + ", "+ ex);
}
De-serialization:
try {
FileInputStream file = new FileInputStream(<filePath>);
ObjectInputStream reader = new ObjectInputStream(file);
while (true) {
try {
YourObject obj = (YourObject)reader.readObject();
System.out.println(obj)
} catch (Exception ex) {
System.err.println("end of reader file ");
break;
}
}
} catch (Exception ex) {
System.err.println("failed to read " + filePath + ", "+ ex);
}

Serializing ArrayList android not working

UPDATE: After a bit of testing I've determined the file itself isnt being created, at least according to the file.exists check anyway. Any ideas?
Hi I'm trying to serialize an arraylist when my app is exited and read it back when its resumed. It doesnt seem to be creating the file.
Here is my code.
protected void onPause() {
super.onPause();
if(!myArrayList.isEmpty())
{
final String FILENAME = "myfile.bin";
try{
FileOutputStream fos;
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
//FileOutputStream fileStream = new FileOutputStream(FILENAME);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(myArrayList);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
#SuppressWarnings("unchecked")
#Override
protected void onResume() {
super.onResume();
File file = new File("myfile.bin");
if(file.exists()){
final String FILENAME="myfile.bin";
try{
FileInputStream fileStream = new FileInputStream(FILENAME);
ObjectInputStream os = new ObjectInputStream(fileStream);
myArrayList = (ArrayList<MyObject>)os.readObject();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
Any ideas? My MyObject class implements serializable.
Got it to work by changing FileInputStream fileStream = new FileInputStream(FILENAME) to FileInputStream fileStream= openFileInput(FILENAME).
os.writeObject(myArrayList);
os.flush();
os.close();
Try os.close() immediately after writeObject, it should call flush() anyways.

Categories

Resources