Android学习笔记之数据的内部存储方式实习数据的读写、存储到Cache实现读写
2015-01-18 14:12
423 查看
(1)目录结构
(2) 布局文件:
(3)保存数据、读取数据的工具类:FileService.java
package com.example.data_storage_interal.file;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
/**
* 使用内部存储的方式,可以使应用卸载的时候清除所有的相关信息
*
* @author piaodangdehun
*
*/
public class FileService {
private Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 保存内容到文件中
*
* @param fileName
* : 文件名
* @param mode
* :模式
* @param data
* :数据的缓冲区
* @return 返回真假值
*/
public boolean saveContentToFile(String fileName, int mode, byte[] data) {
boolean flag = false;
FileOutputStream outputStream = null;
try {
outputStream = context.openFileOutput(fileName, mode);
try {
outputStream.write(data, 0, data.length);
} catch (IOException e) {
e.printStackTrace();
}
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
}
}
}
return true;
}
/**
* 读取数据
*
* @param fileName
* @return
*/
public String readContentFromFile(String fileName) {
String result = "";
FileInputStream fileInputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
fileInputStream = context.openFileInput(fileName);
int len = 0;
byte[] data = new byte[1024];
while ((len = fileInputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
return new String(outputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/*
* 保存文件到Chace中
*/
public boolean saveCacheFile(String fileName, byte[] data) {
boolean flag = false;
File file = context.getFilesDir();
FileOutputStream outputStream = null;
try {
File folderFile = new File(file.getAbsoluteFile() + "/txt");
if (!folderFile.exists()) {
folderFile.mkdirs();// 创建目录
}
// context.openFileOutput("my.txt", context.MODE_WORLD_READABLE);
outputStream = new FileOutputStream(folderFile.getAbsolutePath()
+ "/" + fileName);
try {
outputStream.write(data, 0, data.length);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// System.out.println("-->>"+file.getAbsolutePath());
return flag;
}
/*
* 获得文件的完整路径
*/
public void listCacheFile() {
/*
* String[] strings = context.fileList(); for (int i = 0; i <
* strings.length; i++) { System.out.println("-->>" + strings); }
*/
File file = context.getFilesDir();
File root = new File(file.getAbsoluteFile() + "/txt");
File[] listFiles = root.listFiles();
for (File file2 : listFiles) {
System.err.println("--->>" + file2.getAbsolutePath());
}
}
}
(4)MainActivity.java
(5)测试类(要在资源文件中添加相应的信息、这里不说)
package com.example.data_storage_interal;
import com.example.data_storage_interal.file.FileService;
import android.app.Service;
import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;
public class MyTest extends AndroidTestCase {
private static final String TAG = "MyTest";
/*
* 保存数据
*/
public void save() {
FileService fileService = new FileService(getContext());
boolean flag = fileService.saveContentToFile("aa.txt",
Context.MODE_PRIVATE + Context.MODE_APPEND, "nihao".getBytes());
Log.i(TAG, "--->>" + flag);
}
/*
* 保存数据
*/
public void read() {
FileService fileService = new FileService(getContext());
String msg = fileService.readContentFromFile("bb.txt");
Log.i(TAG, "--->>" + msg);
}
public void testChaceFile() {
FileService fileService = new FileService(getContext());
fileService.saveCacheFile("hello.txt", "hello world!".getBytes());
}
public void testListFile() {
FileService fileService = new FileService(getContext());
fileService.listCacheFile();
}
}
保存成功后会在data-data-apk的安装目录下找到相应的文件:
(2) 布局文件:
<RelativeLayout 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" tools:context=".MainActivity" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="28dp" android:layout_marginTop="17dp" android:ems="10" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginTop="54dp" android:text="保存信息" /> </RelativeLayout>
(3)保存数据、读取数据的工具类:FileService.java
package com.example.data_storage_interal.file;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
/**
* 使用内部存储的方式,可以使应用卸载的时候清除所有的相关信息
*
* @author piaodangdehun
*
*/
public class FileService {
private Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 保存内容到文件中
*
* @param fileName
* : 文件名
* @param mode
* :模式
* @param data
* :数据的缓冲区
* @return 返回真假值
*/
public boolean saveContentToFile(String fileName, int mode, byte[] data) {
boolean flag = false;
FileOutputStream outputStream = null;
try {
outputStream = context.openFileOutput(fileName, mode);
try {
outputStream.write(data, 0, data.length);
} catch (IOException e) {
e.printStackTrace();
}
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
}
}
}
return true;
}
/**
* 读取数据
*
* @param fileName
* @return
*/
public String readContentFromFile(String fileName) {
String result = "";
FileInputStream fileInputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
fileInputStream = context.openFileInput(fileName);
int len = 0;
byte[] data = new byte[1024];
while ((len = fileInputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
return new String(outputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/*
* 保存文件到Chace中
*/
public boolean saveCacheFile(String fileName, byte[] data) {
boolean flag = false;
File file = context.getFilesDir();
FileOutputStream outputStream = null;
try {
File folderFile = new File(file.getAbsoluteFile() + "/txt");
if (!folderFile.exists()) {
folderFile.mkdirs();// 创建目录
}
// context.openFileOutput("my.txt", context.MODE_WORLD_READABLE);
outputStream = new FileOutputStream(folderFile.getAbsolutePath()
+ "/" + fileName);
try {
outputStream.write(data, 0, data.length);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// System.out.println("-->>"+file.getAbsolutePath());
return flag;
}
/*
* 获得文件的完整路径
*/
public void listCacheFile() {
/*
* String[] strings = context.fileList(); for (int i = 0; i <
* strings.length; i++) { System.out.println("-->>" + strings); }
*/
File file = context.getFilesDir();
File root = new File(file.getAbsoluteFile() + "/txt");
File[] listFiles = root.listFiles();
for (File file2 : listFiles) {
System.err.println("--->>" + file2.getAbsolutePath());
}
}
}
(4)MainActivity.java
package com.example.data_storage_interal; import com.example.data_storage_interal.file.FileService; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private Button button; private EditText editText; private FileService fileService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button1); editText = (EditText) this.findViewById(R.id.editText1); fileService = new FileService(this); /* * 按钮点击的时候存放到文件中 */ button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String valueString = editText.getText().toString().trim(); boolean flag = fileService.saveContentToFile("bb.txt", Context.MODE_APPEND, valueString.getBytes()); if (flag) { Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_SHORT).show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
(5)测试类(要在资源文件中添加相应的信息、这里不说)
package com.example.data_storage_interal;
import com.example.data_storage_interal.file.FileService;
import android.app.Service;
import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;
public class MyTest extends AndroidTestCase {
private static final String TAG = "MyTest";
/*
* 保存数据
*/
public void save() {
FileService fileService = new FileService(getContext());
boolean flag = fileService.saveContentToFile("aa.txt",
Context.MODE_PRIVATE + Context.MODE_APPEND, "nihao".getBytes());
Log.i(TAG, "--->>" + flag);
}
/*
* 保存数据
*/
public void read() {
FileService fileService = new FileService(getContext());
String msg = fileService.readContentFromFile("bb.txt");
Log.i(TAG, "--->>" + msg);
}
public void testChaceFile() {
FileService fileService = new FileService(getContext());
fileService.saveCacheFile("hello.txt", "hello world!".getBytes());
}
public void testListFile() {
FileService fileService = new FileService(getContext());
fileService.listCacheFile();
}
}
保存成功后会在data-data-apk的安装目录下找到相应的文件:
相关文章推荐
- Android实现数据存储的5种方式
- Android实现数据存储技术 (5中存储方式) 基础中的基础!!!!
- 数据存储详解(二)---->File存储:内部存储 -Cache和外部存储-SD卡
- 安卓存储数据和文件系列1:读写sdCard方式
- Android数据存储实现的5大方式
- Windows Phone开发之独立存储、文件的读写、ListBox绑定数据、NavigationService实现XAML跳转
- Android数据存储实现的5大方式
- Android第六讲——数据存储(五种)SharedPreferences、内部存储(缓存cache)、外部存储(Sdcrad)、SQLite数据库、网络存储
- Android数据存储实现的5大方式
- 数据结构实现之Table(符号表,内部存储key-value对)
- Nand Flash数据存储方式和数据读写方法!
- ArrayList、List<T>、HashSet<T>、LinkedList<T>各自优点和缺点,Dictionary<K,V>的内部存储数据方式有什么特殊的?
- 读写内部存储的文件数据
- Android学习笔记-------数据的四种存储方式
- 怎样实现IOS开发中的数据存储方式
- Android学习笔记十四.Android数据存储与IO.SD卡的读写实例
- 设备驱动中环形缓冲区数据存储和读写同步的实现[转自:http://hi.baidu.com/whandsome/blog/item/3834e32a9994692cd52af1f9.html]
- Android数据存储实现的5大方式
- 读写内部存储的文件数据
- Android 数据存储方式(一.文件+内部外部存储吐血详解)