保存一个ArrayList到文件上的android [英] Save an ArrayList to File on android

查看:681
本文介绍了保存一个ArrayList到文件上的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ArrayList完全用户填充它在不同的活动中使用一个ListView,查看他们已经保存了弦弦。 我想他们填充ArrayList中保存,但我这样失去如何得到它的工作。我试过的FileOutputStream,共享preferences。我看了很多例子。

I have an ArrayList full of strings that the user populated it with to use in a different activity in a ListView to view the strings they have saved. I want the ArrayList they populated to be saved but I am so lost on how to get it to work. I've tried FileOutputStream, SharedPreferences. I looked at many examples.

例如,我有

ArrayList<String> give = new ArrayList<String>();

和保存ArrayList的香港专业教育学院尝试过的东西,如

and to save the arraylist ive tried stuff like

FileOutputStream fos = openFileOutput(MYFILENAME, Context.MODE_PRIVATE);
fos.write(give.getBytes());
fos.close();

但是,这并不在所有的工作

but this does not work at all

推荐答案

下面是一些code采取序列化的对象,并将其写入到文件,这可能是你所需要的。经测试它与和ArrayList和正常工作。您也可以修改输出,而不是写入到文件,你可以使用额外的或它的捆绑它传递给一个活动。我用这个方法对于Android版本&LT; 3.0。

Here is some code to take a serializable object and write it to file, this maybe what you need. Tested it out with and ArrayList and it works fine. You can also modify the output and instead of writing it to file you can pass it to an activity using extras or its bundle. I used this method for android versions < 3.0.

要读取一个文件已经包含序列化对象:

To Read a file already containing serialized object:

String ser = SerializeObject.ReadSettings(act, "myobject.dat");
if (ser != null && !ser.equalsIgnoreCase("")) {
    Object obj = SerializeObject.stringToObject(ser);
    // Then cast it to your object and 
    if (obj instanceof ArrayList) {
        // Do something
        give = (ArrayList<String>)obj;
    }
}

要一个对象写入文件中使用:

To Write an object to file use:

String ser = SerializeObject.objectToString(give);
if (ser != null && !ser.equalsIgnoreCase("")) {
    SerializeObject.WriteSettings(act, ser, "myobject.dat");
} else {
    SerializeObject.WriteSettings(act, "", "myobject.dat");
}

类序列化对象:

Class to serialize an object:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;

import android.content.Context;
import android.util.Base64InputStream;
import android.util.Base64OutputStream;
import android.util.Log;

/**
 * Take an object and serialize and then save it to preferences
 * @author John Matthews
 *
 */
public class SerializeObject {
    private final static String TAG = "SerializeObject";

    /**
     * Create a String from the Object using Base64 encoding
     * @param object - any Object that is Serializable
     * @return - Base64 encoded string.
     */
    public static String objectToString(Serializable object) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            new ObjectOutputStream(out).writeObject(object);
            byte[] data = out.toByteArray();
            out.close();

            out = new ByteArrayOutputStream();
            Base64OutputStream b64 = new Base64OutputStream(out,0);
            b64.write(data);
            b64.close();
            out.close();

            return new String(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Creates a generic object that needs to be cast to its proper object
     * from a Base64 ecoded string.
     * 
     * @param encodedObject
     * @return
     */
    public static Object stringToObject(String encodedObject) {
        try {
            return new ObjectInputStream(new Base64InputStream(
                    new ByteArrayInputStream(encodedObject.getBytes()), 0)).readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Save serialized settings to a file
     * @param context
     * @param data
     */
    public static void WriteSettings(Context context, String data, String filename){ 
        FileOutputStream fOut = null; 
        OutputStreamWriter osw = null;

        try{
            fOut = context.openFileOutput(filename, Context.MODE_PRIVATE);       
            osw = new OutputStreamWriter(fOut); 
            osw.write(data); 
            osw.flush(); 
            //Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
        } catch (Exception e) {       
            e.printStackTrace(); 
           // Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
        } 
        finally { 
            try { 
                if(osw!=null)
                    osw.close();
                if (fOut != null)
                    fOut.close(); 
            } catch (IOException e) { 
                   e.printStackTrace(); 
            } 
        } 
    }

    /**
     * Read data from file and put it into a string
     * @param context
     * @param filename - fully qualified string name
     * @return
     */
    public static String ReadSettings(Context context, String filename){ 
        StringBuffer dataBuffer = new StringBuffer();
        try{
            // open the file for reading
            InputStream instream = context.openFileInput(filename);
            // if file the available for reading
            if (instream != null) {
                // prepare the file for reading
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);

                String newLine;
                // read every line of the file into the line-variable, on line at the time
                while (( newLine = buffreader.readLine()) != null) {
                    // do something with the settings from the file
                    dataBuffer.append(newLine);
                }
                // close the file again
                instream.close();
            }

        } catch (java.io.FileNotFoundException f) {
            // do something if the myfilename.txt does not exits
            Log.e(TAG, "FileNot Found in ReadSettings filename = " + filename);
            try {
                context.openFileOutput(filename, Context.MODE_PRIVATE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            Log.e(TAG, "IO Error in ReadSettings filename = " + filename);
        }

        return dataBuffer.toString();
    }

}

这篇关于保存一个ArrayList到文件上的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆