android本地、sd卡保存对象或集合,以及读取该对象
来源:互联网 发布:利郎皮带淘宝 编辑:程序博客网 时间:2024/05/20 18:45
这是一个将对象或集合写入本地还有sd卡以及如何读取的例子,提供大家参考。
转载请说明此处!!
通过以下图片了解本demo的主要功能:
上代码
首先在manifest中添加权限:
<!-- 在SDCard中创建与删除文件的权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 往SDCard写入数据的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
接着创建一个TestClass类用来测试:
public class TestClass implements Serializable{/** * */private static final long serialVersionUID = 1L;private String name;private String gender;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public TestClass(String name, String gender) {super();this.name = name;this.gender = gender;}}
记得改类要实现Serializable接口!!
接下来是将类保存到本地和sd卡的 OutputUtil 类及方法:
package com.example.inputoutputtest;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.util.List;import android.annotation.SuppressLint;import android.content.Context;import android.os.Environment;@SuppressLint("WorldReadableFiles")public class OutputUtil<T> {/** * 将对象保存到本地 * @param context * @param fileName 文件名 * @param bean 对象 * @return true 保存成功 */public boolean writeObjectIntoLocal(Context context,String fileName,T bean){try {// 通过openFileOutput方法得到一个输出流,方法参数为创建的文件名(不能有斜杠),操作模式@SuppressWarnings("deprecation")FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(bean);//写入fos.close();//关闭输入流oos.close();return true;} catch (FileNotFoundException e) { e.printStackTrace(); //Toast.makeText(WebviewTencentActivity.this, "出现异常1",Toast.LENGTH_LONG).show(); return false;} catch (IOException e) { e.printStackTrace(); //Toast.makeText(WebviewTencentActivity.this, "出现异常2",Toast.LENGTH_LONG).show(); return false;} }/** * 将对象写入sd卡 * @param fileName 文件名 * @param bean对象 * @return true 保存成功 */public boolean writObjectIntoSDcard(String fileName,T bean){if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File sdCardDir = Environment.getExternalStorageDirectory();//获取sd卡目录File sdFile = new File(sdCardDir, fileName);try {FileOutputStream fos = new FileOutputStream(sdFile);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(bean);//写入fos.close();oos.close();return true;} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; }}else {return false;}}/** * 将集合写入sd卡 * @param fileName 文件名 * @param list集合 * @return true 保存成功 */public boolean writeListIntoSDcard(String fileName,List<T> list){if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File sdCardDir = Environment.getExternalStorageDirectory();//获取sd卡目录File sdFile = new File(sdCardDir, fileName);try {FileOutputStream fos = new FileOutputStream(sdFile);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(list);//写入fos.close();oos.close();return true;} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; }}else {return false;}}}
有了写入的类,自然还要一个读取的 InputUtil 类以及方法:
package com.example.inputoutputtest;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.ObjectInputStream;import java.io.OptionalDataException;import java.io.StreamCorruptedException;import java.util.List;import android.content.Context;import android.os.Environment;public class InputUtil<T> {/** * 读取本地对象 * @param context * @param fielName 文件名 * @return */@SuppressWarnings("unchecked")public T readObjectFromLocal(Context context,String fielName){T bean;try {FileInputStream fis = context.openFileInput(fielName);//获得输入流 ObjectInputStream ois = new ObjectInputStream(fis);bean = (T) ois.readObject();fis.close();ois.close();return bean;} catch (StreamCorruptedException e) { //Toast.makeText(ShareTencentActivity.this,"出现异常3",Toast.LENGTH_LONG).show();//弹出Toast消息 e.printStackTrace(); return null;} catch (OptionalDataException e) { //Toast.makeText(ShareTencentActivity.this,"出现异常4",Toast.LENGTH_LONG).show();//弹出Toast消息 e.printStackTrace();return null;} catch (FileNotFoundException e) { //Toast.makeText(ShareTencentActivity.this,"出现异常5",Toast.LENGTH_LONG).show();//弹出Toast消息 e.printStackTrace(); return null;} catch (IOException e) { e.printStackTrace(); return null;} catch (ClassNotFoundException e) { //Toast.makeText(ShareTencentActivity.this,"出现异常6",Toast.LENGTH_LONG).show();//弹出Toast消息 e.printStackTrace(); return null;} }/** * 读取sd卡对象 * @param fileName 文件名 * @return */@SuppressWarnings("unchecked")public T readObjectFromSdCard(String fileName){if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //检测sd卡是否存在T bean;File sdCardDir = Environment.getExternalStorageDirectory();File sdFile = new File(sdCardDir,fileName);try {FileInputStream fis = new FileInputStream(sdFile);ObjectInputStream ois = new ObjectInputStream(fis);bean = (T) ois.readObject();fis.close();ois.close();return bean;} catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} catch (OptionalDataException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} }else {return null;}}/** * 读取sd卡对象 * @param fileName 文件名 * @return */@SuppressWarnings("unchecked")public List<T> readListFromSdCard(String fileName){if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //检测sd卡是否存在List<T> list;File sdCardDir = Environment.getExternalStorageDirectory();File sdFile = new File(sdCardDir,fileName);try {FileInputStream fis = new FileInputStream(sdFile);ObjectInputStream ois = new ObjectInputStream(fis);list = (List<T>) ois.readObject();fis.close();ois.close();return list;} catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} catch (OptionalDataException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return null;} }else {return null;}}}
封装完这些类后,接下来就是使用它们了。
在布局文件activity_main中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" android:gravity="center_horizontal" android:background="#000000" tools:context=".MainActivity" ><TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textSize="20sp" android:textStyle="bold" android:textColor="#ffffff" android:text="对象的保存"/> <Button android:id="@+id/output_loacl" android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#ffffff" android:text="写入本地" /> <Button android:id="@+id/input_loacl" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#ffffff" android:text="从本地读出" /> <Button android:id="@+id/output_sdcard" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#ffffff" android:text="写入SD卡" /> <Button android:id="@+id/input_sdcard" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#ffffff" android:text="从SD卡读出" /> <Button android:id="@+id/output_sdcard_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#ffffff" android:text="写入SD卡(集合)" /> <Button android:id="@+id/input_sdcard_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#ffffff" android:text="从SD卡读出(集合)" /></LinearLayout>
最后是在MainActivity 中:
package com.example.inputoutputtest;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener {private Button output_loacl;private Button input_loacl;private Button output_sdcard;private Button input_sdcard;private Button output_sdcard_list;private Button input_sdcard_list;private TestClass bean;private List<TestClass> list;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}/** * 初始化 */private void init() {output_loacl = (Button) findViewById(R.id.output_loacl);input_loacl = (Button) findViewById(R.id.input_loacl);output_sdcard = (Button) findViewById(R.id.output_sdcard);input_sdcard = (Button) findViewById(R.id.input_sdcard);output_sdcard_list = (Button) findViewById(R.id.output_sdcard_list);input_sdcard_list = (Button) findViewById(R.id.input_sdcard_list);output_loacl.setOnClickListener(this);input_loacl.setOnClickListener(this);output_sdcard.setOnClickListener(this);input_sdcard.setOnClickListener(this);output_sdcard_list.setOnClickListener(this);input_sdcard_list.setOnClickListener(this);bean = new TestClass("华少", "男");list = new ArrayList<TestClass>();list.add(new TestClass("小米", "女"));list.add(bean);}/** * write into local * @param bean */private void writeIntoLocal(TestClass bean){if (new OutputUtil<TestClass>().writeObjectIntoLocal(MainActivity.this, "test.out", bean)) {Toast.makeText(MainActivity.this, "写入本地成功", 2000).show();}else {Toast.makeText(MainActivity.this, "写入本地失败", 2000).show();}}/** * rean from loacl */private void readFormLoacl(){TestClass bean1 = new InputUtil<TestClass>().readObjectFromLocal(MainActivity.this, "test.out");if (bean1 == null) {Toast.makeText(MainActivity.this, "本地读取失败", 2000).show();}else {Toast.makeText(MainActivity.this, "本地读取成功"+bean1.getName()+"-"+bean1.getGender(), 2000).show();}}/** * write into sdcard * @param bean */private void writeIntoSDcard(TestClass bean){if (new OutputUtil<TestClass>().writObjectIntoSDcard("test.out", bean)) {Toast.makeText(MainActivity.this, "写入SD卡成功", 2000).show();}else {Toast.makeText(MainActivity.this, "写入SD卡失败", 2000).show();}}/** * rean from sdcard */private void readFromSDcard(){TestClass bean1 = new InputUtil<TestClass>().readObjectFromSdCard("test.out");if (bean1 == null) {Toast.makeText(MainActivity.this, "SD卡读取失败", 2000).show();}else {Toast.makeText(MainActivity.this, "SD卡读取成功"+bean1.getName()+"-"+bean1.getGender(), 2000).show();}}/** * write into sdcard (object) * @param list */private void writeListIntoSDcard(List<TestClass> list){if (new OutputUtil<TestClass>().writeListIntoSDcard("testlist.out", list)) {Toast.makeText(MainActivity.this, "写入SD卡成功", 2000).show();}else {Toast.makeText(MainActivity.this, "写入SD卡失败", 2000).show();}}/** * rean from sdcard (集合) */private void readListFromSDcard(){List<TestClass> list = new InputUtil<TestClass>().readListFromSdCard("testlist.out");if (list == null) {Toast.makeText(MainActivity.this, "SD卡读取失败", 2000).show();}else {StringBuffer sb = new StringBuffer();for (int i = 0; i < list.size(); i++) {sb.append(list.get(i).getName());sb.append(list.get(i).getGender());}Toast.makeText(MainActivity.this, "SD卡读取成功"+sb, 2000).show();}}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.output_loacl:writeIntoLocal(bean);break;case R.id.input_loacl:readFormLoacl();break;case R.id.output_sdcard:writeIntoSDcard(bean);break;case R.id.input_sdcard:readFromSDcard();break;case R.id.output_sdcard_list:writeListIntoSDcard(list);break;case R.id.input_sdcard_list:readListFromSDcard();break;default:break;}}}
这样就大功告成了。
附:demo代码 点击打开链接
转载请说明出处
若有错误之处,感谢指出
2 0
- android本地、sd卡保存对象或集合,以及读取该对象
- android本地、sd卡保存对象或集合,以及读取该对象
- Android SharedPreferences保存对象以及读取对象信息
- android保存图片到本地sd卡
- Android 保存View到本地SD卡
- Android文件的保存(本地和SD卡)与读取
- Android使用sd卡保存读取数据
- Android 读取本地(SD卡)图片
- Android 读取本地(SD卡)图片
- Android 读取本地(SD卡)图片
- Android 使用LitePal将list(String,对象,集合)数据保存到本地数据库
- Android 从本地SD卡中读取图片以及编辑图片
- Android SharedPreferences保存和读取对象
- android保存读取对象 SharedPreferences方式
- sharedPrefrence保存读取对象
- Android捕获异常保存SD卡或上传服务器
- android,保存文件到sd卡和读取
- Android将bitemap保存在SD卡并读取
- 怎样在DevExpress XtraTreeList中设置ToolTip?
- MindMapper思维导图该怎样进行美化
- Console命令详解,让调试js代码变得更简单
- SQL中的联合查询
- solr配置说明
- android本地、sd卡保存对象或集合,以及读取该对象
- 怎么把威纶触摸屏上的程序上存到u盘上?
- Linux查看文件和文件夹大小
- 二值图像的膨胀运算及其VC实现
- Java 抽象类
- 查询索引中的碎片和重建SQL server索引
- 武汉软件工程职业学院与传智播客签约达成深度校企合作
- iOS开发拓展篇—CoreLocation定位服务
- 启动TOMCAT报错 java.util.zip.ZipException: invalid LOC header (bad signature)