本文整理资料来自《android开发权威指南》
文件存储中主要有两个方法openFileOutput和openFileInput。
使用文件保存的数据在/data/data/<package name>/file目录中。
1、下面是向文件中写入和读取数据的代码:
public void fileStore()
{
try
{
//像指定文件写入内容
OutputStream os = openFileOutput("file.txt", Activity.MODE_PRIVATE);
String str1 = "《android、ophone开发完全讲义》";
os.write(str1.getBytes("utf-8"));
os.close();
//读取文件
InputStream is = openFileInput("file.txt");
byte[] buffer = new byte[100];
int byteCount = is.read(buffer);
String str2 = new String(buffer,0,byteCount,"utf-8");
TextView textView = (TextView) findViewById(R.id.text);
textView.setText(str2);
is.close();
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2、读写SD卡中的文件。
代码如下:
//向SD卡保存图片
public void store_Image(View view)
{
try
{
//将创建用于将图像保存到SD卡上的FileOutputStream对象
FileOutputStream fos = new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+"/image.jpg");
//打开assets目录中的image.jpg文件,并返回InputStream对象
InputStream is = getResources().getAssets().open("image.jpg");
//定义一个byte数组,用于保存每次向SD卡中文件写入的数据,最多8k
byte[] buffer = new byte[8192];
int count = 0;
//循环写入数据
while ((count = is.read(buffer))>=0)
{
fos.write(buffer,0,count);
}
fos.close();
is.close();
Toast.makeText(this, "已成功将图像文件写入SD卡上", Toast.LENGTH_LONG).show();
} catch (Exception e)
{
// TODO: handle exception
}
}
//读取SD卡图片
public void read_Image(View view)
{
//指定SD卡中的图像文件名
String fileName = android.os.Environment.getExternalStorageDirectory()+"/image.jpg";
//判断是否存在
if(!new File(fileName).exists())
{
Toast.makeText(this, "还没人往SD卡写入数据", Toast.LENGTH_SHORT).show();
return;
}
ImageView imageView = (ImageView) findViewById(R.id.image);
try
{
FileInputStream fis = new FileInputStream(fileName);
//从文件的输入流装载bitmap
Bitmap bitmap = BitmapFactory.decodeStream(fis);
//将图像显示出来在ImageView上
imageView.setImageBitmap(bitmap);
try
{
fis.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
在默认情况下,是不允许对SD卡中写文件。需要在androidManifest.xml中加入以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
运行效果为:
如需源码
请通过链接下载: