android 文件对象,Android实现文件的保存与读取功能示例

本文实例讲述了Android实现文件的保存与读取功能。分享给大家供大家参考,具体如下:

注: 在Activity中有 getFileDir() 和 getCacheDir(); 方法可以获得当前的手机自带的存储空间中的当前包文件的路径

getFileDir() ----- /data/data/cn.xxx.xxx(当前包)/files

getCacheDir() ----- /data/data/cn.xxx.xxx(当前包)/cache

1. 编写文件读取与写入功能实现类 FileService

package cn.android.service;

import java.io.ByteArrayOutputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import android.content.Context;

import android.util.Log;

/**

* 文件保存与读取功能实现类

* @author Administrator

*

* 2010-6-28 下午08:15:18

*/

public class FileService {

public static final String TAG = "FileService";

private Context context;

//得到传入的上下文对象的引用

public FileService(Context context) {

this.context = context;

}

/**

* 保存文件

*

* @param fileName 文件名

* @param content 文件内容

* @throws Exception

*/

public void save(String fileName, String content) throws Exception {

// 由于页面输入的都是文本信息,所以当文件名不是以.txt后缀名结尾时,自动加上.txt后缀

if (!fileName.endsWith(".txt")) {

fileName = fileName + ".txt";

}

byte[] buf = fileName.getBytes("iso8859-1");

Log.e(TAG, new String(buf,"utf-8"));

fileName = new String(buf,"utf-8");

Log.e(TAG, fileName);

// Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND

// Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。

// Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。

// MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。

// 如果希望文件被其他应用读和写,可以传入:

// openFileOutput("output.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

FileOutputStream fos = context.openFileOutput(fileName, context.MODE_PRIVATE);

fos.write(content.getBytes());

fos.close();

}

/**

* 读取文件内容

*

* @param fileName 文件名

* @return 文件内容

* @throws Exception

*/

public String read(String fileName) throws Exception {

// 由于页面输入的都是文本信息,所以当文件名不是以.txt后缀名结尾时,自动加上.txt后缀

if (!fileName.endsWith(".txt")) {

fileName = fileName + ".txt";

}

FileInputStream fis = context.openFileInput(fileName);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buf = new byte[1024];

int len = 0;

//将读取后的数据放置在内存中---ByteArrayOutputStream

while ((len = fis.read(buf)) != -1) {

baos.write(buf, 0, len);

}

fis.close();

baos.close();

//返回内存中存储的数据

return baos.toString();

}

}

2. 编写Activity类:

package cn.android.test;

import android.app.Activity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import cn.android.service.FileService;

public class TestAndroidActivity extends Activity {

/** Called when the activity is first created. */

//得到FileService对象

private FileService fileService = new FileService(this);

//定义视图中的filename输入框对象

private EditText fileNameText;

//定义视图中的contentText输入框对象

private EditText contentText;

//定义一个土司提示对象

private Toast toast;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

//得到视图中的两个输入框和两个按钮的对象引用

Button button = (Button)this.findViewById(R.id.button);

Button read = (Button)this.findViewById(R.id.read);

fileNameText = (EditText) this.findViewById(R.id.filename);

contentText = (EditText) this.findViewById(R.id.content);

//为保存按钮添加保存事件

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String fileName = fileNameText.getText().toString();

String content = contentText.getText().toString();

//当文件名为空的时候,提示用户文件名为空,并记录日志。

if(isEmpty(fileName)) {

toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG);

toast.setMargin(RESULT_CANCELED, 0.345f);

toast.show();

Log.w(fileService.TAG, "The file name is empty");

return;

}

//当文件内容为空的时候,提示用户文件内容为空,并记录日志。

if(isEmpty(content)) {

toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_content, Toast.LENGTH_LONG);

toast.setMargin(RESULT_CANCELED, 0.345f);

toast.show();

Log.w(fileService.TAG, "The file content is empty");

return;

}

//当文件名和内容都不为空的时候,调用fileService的save方法

//当成功执行的时候,提示用户保存成功,并记录日志

//当出现异常的时候,提示用户保存失败,并记录日志

try {

fileService.save(fileName, content);

toast = Toast.makeText(TestAndroidActivity.this, R.string.success, Toast.LENGTH_LONG);

toast.setMargin(RESULT_CANCELED, 0.345f);

toast.show();

Log.i(fileService.TAG, "The file save successful");

} catch (Exception e) {

toast = Toast.makeText(TestAndroidActivity.this, R.string.fail, Toast.LENGTH_LONG);

toast.setMargin(RESULT_CANCELED, 0.345f);

toast.show();

Log.e(fileService.TAG, "The file save failed");

}

}

});

//为读取按钮添加读取事件

read.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

//得到文件名输入框中的值

String fileName = fileNameText.getText().toString();

//如果文件名为空,则提示用户输入文件名,并记录日志

if(isEmpty(fileName)) {

toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG);

toast.setMargin(RESULT_CANCELED, 0.345f);

toast.show();

Log.w(fileService.TAG, "The file name is empty");

return;

}

//调用fileService的read方法,并将读取出来的内容放入到文本内容输入框里面

//如果成功执行,提示用户读取成功,并记录日志。

//如果出现异常信息(例:文件不存在),提示用户读取失败,并记录日志。

try {

contentText.setText(fileService.read(fileName));

toast = Toast.makeText(TestAndroidActivity.this, R.string.read_success, Toast.LENGTH_LONG);

toast.setMargin(RESULT_CANCELED, 0.345f);

toast.show();

Log.i(fileService.TAG, "The file read successful");

} catch (Exception e) {

toast = Toast.makeText(TestAndroidActivity.this, R.string.read_fail, Toast.LENGTH_LONG);

toast.setMargin(RESULT_CANCELED, 0.345f);

toast.show();

Log.e(fileService.TAG, "The file read failed");

}

}

});

}

//编写一个isEmpty方法,判断字符串是否为空

private boolean isEmpty(String s) {

if(s == null || "".equals(s.trim())) {

return true;

}

return false;

}

}

3.文件布局文件:main.xml

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/filename"

/>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/filename"

/>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/content"

/>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:minLines="3"

android:id="@+id/content"

/>

android:orientation="horizontal"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/button"

android:text="@string/save"

/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/read"

android:text="@string/read"

/>

PS:由于我在测试这个功能的时候发现文件名无法使用中文(sdk2.2 + 模拟器),如果有哪为高手无意中浏览此文章后,能对这个问题予以指点,我将感激不尽。呵呵。

希望本文所述对大家Android程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值