Serializing ArrayList android not working - java

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.

Related

Writing a HashMap to a text file Android studio

I have tried to use serialisation to write my HashMap into a text file but it just doesn't seem to work. I'm not sure if I'm using it wrong
my Hashmap :
HashMap lettersAvailable = new HashMap();
and my code I use for serialisation
public void onResume(){
super.onResume();
try
{
FileInputStream fileInputStream = new FileInputStream(getApplicationContext().getFilesDir()+"/FenceInformation.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map lettersAvailable = (Map)objectInputStream.readObject();
Toast.makeText(this,"Hashmap reloaded",Toast.LENGTH_SHORT);
}
catch(ClassNotFoundException | IOException | ClassCastException e) {
e.printStackTrace();
}
}
#Override
public void onPause(){
super.onPause();
try
{
FileOutputStream fos = getApplicationContext().openFileOutput("YourInfomration.ser", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(lettersAvailable);
oos.close();
Log.d(TAG, "onCreate() Restoring previous state");
} catch (IOException e) {
e.printStackTrace();
}
}
In the onResume method it says lettersAvailable variable is never used at Maps lettersAvailable
Is there not another way to do this?

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); }

Writing,reading and deleting objects into file in java

I want write list of objects into file, and then reading it one by one, and deleting respectively.
Writing and reading functions are below. For one by one reading,first I read all, then pop first, and other write to file again. it very ineffective and takes long time. So, what should I do to get better perfomance? Or maybe, there are other variant to solve this problem
public void writeToDisk(String filePath,TreeMap<String, ArrayList<Integer>> obj){
File file = new File(filePath);
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
ObjectOutputStream o = new ObjectOutputStream(fout);
o.writeObject(obj);
o.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TreeMap<String, ArrayList<Integer>> readFromDisk(String filePath){
TreeMap<String,ArrayList<Integer>> invertIndexMap = null;
File file = new File(filePath);
FileInputStream f;
try {
f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
invertIndexMap = (TreeMap<String, ArrayList<Integer>>) s.readObject();
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return invertIndexMap;
}

reading objects from file

I have a problem with reading objects from file Java.
file is anarraylist<projet>
This is the code of saving objects :
try {
FileOutputStream fileOut = new FileOutputStream("les projets.txt", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (projet a : file) {
out.writeObject(a);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
And this is the code of reading objects from file ::
try {
FileInputStream fileIn = new FileInputStream("les projets.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (in.available() > 0){
projet c = (projet) in.readObject();
b.add(c);
}
choisir = new JList(b.toArray());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Writing is working properly. The problem is the reading... it does not read any object (projet) What could be the problem?
As mentioned by EJP in comment and this SO post . if you are planning to write multiple objects in a single file you should write custom ObjectOutputStream , because the while writing second or nth object header information the file will get corrupt.
As suggested by EJP write as ArrayList , since ArrayList is already Serializable you should not have issue. as
out.writeObject(file) and read it back as ArrayList b = (ArrayList) in.readObject();
for some reason if you cant write it as ArrayList. create custome ObjectOutStream as
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
and change your writeObject as
try {
FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true);
MyObjectOutputStream out = new MyObjectOutputStream(fileOut );
for (projet a : file) {
out.writeObject(a);
}
out.close();
}
catch(Exception e)
{e.printStackTrace();
}
and change your readObject as
ObjectInputStream in = null;
try {
FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt");
in = new ObjectInputStream(fileIn );
while(true) {
try{
projet c = (projet) in.readObject();
b.add(c);
}catch(EOFException ex){
// end of file case
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

android what is wrong with openFileOutput?

I'm trying to use openFileOutput function but it doesn't compile and doesn't recognize the function. I'm using android sdk 1.6. Is this a sdk problem ? Is this a parameter problem ?
import java.io.FileOutputStream;
public static void save(String filename, MyObjectClassArray[] theObjectAr) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObjectAr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
Your method should be as follows. Takes in an extra Context as a parameter. To this method you can pass your Service or Activity
public static void save(String filename, MyObjectClassArray[] theObjectAr,
Context ctx) {
FileOutputStream fos;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObjectAr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
You're trying invoke non-static method from static context (your method has static modifier). You either have to make your method to be non-static or to pass in an instance of Context (activity instance in most cases) and invoke the method on the object.
Also you can't openOutputStream on a path. It causes this exception:
java.lang.IllegalArgumentException: File /storage/sdcard0/path/to/file.txt contains a path separator
To fix this you need to create a file object and just create it like this:
String filename = "/sdcard/path/to/file.txt";
File sdCard = Environment.getExternalStorageDirectory();
filename = filename.replace("/sdcard", sdCard.getAbsolutePath());
File tempFile = new File(filename);
try
{
FileOutputStream fOut = new FileOutputStream(tempFile);
// fOut.write();
// fOut.getChannel();
// etc...
fOut.close();
}catch (Exception e)
{
Log.w(TAG, "FileOutputStream exception: - " + e.toString());
}
You can use openFileOutput in static Class if you pass View as below:
public static void save(View v, String fileName , String message){
FileOutputStream fos = null;
try {
fos = v.getContext().openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(message.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources