欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android 开发 文件读写应用案例分析

程序员文章站 2023-12-05 17:08:10
一、基本概念 在android应用中保存文件,保存的位置有两处 ①手机自带的存储空间,较小(如200m),适合保存一些小文件,android中保存位置在data/data/...
一、基本概念
在android应用中保存文件,保存的位置有两处
①手机自带的存储空间,较小(如200m),适合保存一些小文件,android中保存位置在data/data/应用包名/files目录
②外存储设备如sd卡,较大,适合保存大文件如视频,android中保存位置在mnt/sdcard目录,androd1.5,android1.6保存在sdcard目录
保存的位置通过android的file explorer视图可以找到

二、例子
复制代码 代码如下:

/**
* 文件操作类
*
* @author xy
*
*/
public class fileservice
{
/**
* 上下文对象
*/
private context context;
public fileservice(context context)
{
super();
this.context = context;
}
/**
* 保存文件至手机自带的存储空间
*
* @param filename 文件名
* @param filecontent 文件内容
*/
@suppresswarnings("static-access")
public void save(string filename, string filecontent) throws exception
{
fileoutputstream fos = context.openfileoutput(filename, context.mode_private); // 默认保存在手机自带的存储空间
fos.write(filecontent.getbytes("utf-8"));
fos.close();
}
/**
* 保存文件至sd卡
*
* @param filename 文件名
* @param filecontent 文件内容
*/
public void saveinsdcard(string filename, string filecontent) throws exception
{
// 若文件被保存在sdcard中,该文件不受读写控制
file file = new file(environment.getexternalstoragedirectory(), filename);
fileoutputstream fos = new fileoutputstream(file);
fos.write(filecontent.getbytes("utf-8"));
fos.close();
}
/**
* 读取文件内容
*
* @param filename 文件名
* @return
*/
public string read(string filename) throws exception
{
fileinputstream fis = context.openfileinput(filename);
bytearrayoutputstream outstream = new bytearrayoutputstream();
byte[] buffer = new byte[1024];
int len = 0;
// 将内容读到buffer中,读到末尾为-1
while ((len = fis.read(buffer)) != -1)
{
// 本例子将每次读到字节数组(buffer变量)内容写到内存缓冲区中,起到保存每次内容的作用
outstream.write(buffer, 0, len);
}
// 取内存中保存的数据
byte[] data = outstream.tobytearray();
fis.close();
string result = new string(data, "utf-8");
return result;
}
}

mainactivity
复制代码 代码如下:

try
{
// 存储在手机自带存储空间
fs.save(filename, filecontent);
toast.maketext(getapplicationcontext(), r.string.success, toast.length_short).show();
// 存储在外部设备sd卡
// 判断sdcard是否存在和是否可读写
if (environment.getexternalstoragestate().equals(environment.media_mounted))
{
fs.saveinsdcard(filename, filecontent);
toast.maketext(getapplicationcontext(), r.string.success, toast.length_short).show();
}
else
{
toast.maketext(getapplicationcontext(), r.string.failsdcard, toast.length_short).show();
}
}
catch (exception e)
{
toast.maketext(getapplicationcontext(), r.string.fail, toast.length_short).show();
log.e(tag, e.getmessage());
}

文件名不带路径,直接输入如xy.txt
对于sd卡的操作,需要在androidmanifest.xml加入权限
复制代码 代码如下:

<!-- 在sdcard中创建和删除文件的权限 -->
<uses-permission android:name="android.permission.mount_unmount_filesystems" />
<!-- 往sdcard中写入数据的权限 -->
<uses-permission android:name="android.permission.write_external_storage" />


三、一些api
①environment.getexternalstoragedirectory()获取的路径为mnt/sdcard目录,对于android1.5,1.6的路径是sdcard目录
②activity中提供了两个api
getcachedir()获取的路径为data/data/应用包名/cache目录
getfilesdir()获取的路径为data/data/应用包名/files目录