原文地址:点击打开链接
在Android中读写文件可以采用两种方式:一种是采用JDK提供的FileInputStream、FileOutputStream这些类来操作,另一种是采用Android的Context类自带的一些方法操作,如FileOutputStream openFileOutput(String name, int mode)方法用于写文件,FileInputStream openFileInput(String name)方法用于读文件。
mode有四种模式,分别为:
Context.MODE_PRIVATE = 0
Context.MODE_APPEND = 32768
Context.MODE_WORLD_READABLE = 1
Context.MODE_WORLD_WRITEABLE = 2
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
如果希望文件被其他应用读和写,可以传入:
openFileOutput("test.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
SDcard的读写访问
一般手机的存储空间不是很大,存放些小文件还行,如果要存放像视频这样的大文件,是不可行的。对于像视频这样的大文件,我们可以把它存放在SDCard。 SDCard是干什么的?你可以把它看作是移动硬盘或U盘。
在模拟器中使用SDCard,你需要先创建一张SDCard卡(当然不是真的SDCard,只是镜像文件)。创建SDCard可以在Eclipse创建模拟器时随同创建,也可以使用DOS命令进行创建,如下:
在Dos窗口中进入android SDK安装路径的tools目录,输入以下命令创建一张容量为2G的SDCard,文件后缀可以随便取,建议使用.img:
mksdcard 2048M D:\AndroidTool\sdcard.img
在程序中访问SDCard,你需要申请访问SDCard的权限。
在AndroidManifest.xml中加入访问SDCard的权限如下:
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
要往SDCard存放文件,程序必须先判断手机是否装有SDCard,并且可以进行读写。
注意:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File saveFile = new File(sdCardDir, “happy.txt”);
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("Happy".getBytes());
outStream.close();
}
Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,当然要获取SDCard的目录,你也可以这样写:
File sdCardDir = new File("/mnt/sdcard"); //获取SDCard目录
File saveFile = new File(sdCardDir, "happy.txt");
//上面两句代码可以合成一句: File saveFile = new File("/mnt/sdcard/happy.txt");
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("Happy ...".getBytes());
outStream.close();
下面列出项目代码以供参考:
AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.geniusxiaoyu.file" android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <uses-library android:name="android.test.runner" />
- <activity android:name=".FileActivity" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- <uses-sdk android:minSdkVersion="8" />
- <instrumentation android:name="android.test.InstrumentationTestRunner"
- android:targetPackage="com.geniusxiaoyu.file" android:label="Tests for My App" />
- <!-- 在SDCard中创建与删除文件权限 -->
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
- <!-- 往SDCard写入数据权限 -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- </manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.geniusxiaoyu.file" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
<activity android:name=".FileActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.geniusxiaoyu.file" android:label="Tests for My App" />
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
res/values/strings.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="hello">Hello World, FileActivity!</string>
- <string name="app_name">文件操作</string>
- <string name="filename">文件名称</string>
- <string name="filecontent">文件内容</string>
- <string name="button">保存文件</string>
- <string name="success">文件保存成功</string>
- <string name="failed">文件保存失败</string>
- <string name="sdcarderror">SDCard不存在或已被写保护了</string>
- </resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, FileActivity!</string>
<string name="app_name">文件操作</string>
<string name="filename">文件名称</string>
<string name="filecontent">文件内容</string>
<string name="button">保存文件</string>
<string name="success">文件保存成功</string>
<string name="failed">文件保存失败</string>
<string name="sdcarderror">SDCard不存在或已被写保护了</string>
</resources>
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/filename"
- />
- <EditText
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/filename"
- />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/filecontent"
- />
- <EditText
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:minLines="3"
- android:id="@+id/filecontent"
- />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/button"
- android:id="@+id/button"
- />
- </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/filename"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/filename"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/filecontent"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="3"
android:id="@+id/filecontent"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
</LinearLayout>
src/com/geniusxiaoyu/file/service/FileService.java
- package com.geniusxiaoyu.service;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import android.content.Context;
- import android.os.Environment;
- public class FileService {
- private Context context;
- public FileService(Context context){
- this.context = context;
- }
- /**
- * 保存文件
- * @param filename 文件名
- * @param content 内容
- * @param mode 模式
- * @throws Exception
- */
- public void save(String filename, String content, int mode) throws Exception{
- FileOutputStream fos = context.openFileOutput(filename, mode);
- //写入数据
- fos.write(content.getBytes());
- //关闭输出流
- fos.close();
- }
- /**
- * 保存文件,以私有模式保存
- * @param filename 文件名
- * @param content 内容
- * @throws Exception
- */
- public void save(String filename, String content) throws Exception{
- save(filename, content, Context.MODE_PRIVATE);
- }
- /**
- * 往存储卡中写入数据
- * @param filename
- * @param content
- * @throws Exception
- */
- public void saveToSDCard(String filename, String content) throws Exception{
- //SDcard路径在2.2以前是/sdcard,在2.2以上版本中是/mnt/sdcard,最好采用下面的方式灵活获取,适用于所有版本
- File file = new File(Environment.getExternalStorageDirectory(), filename);
- FileOutputStream fos = new FileOutputStream(file);
- //写入数据
- fos.write(content.getBytes());
- //关闭输出流
- fos.close();
- }
- public String readFile(String filename) throws Throwable{
- FileInputStream fis = context.openFileInput(filename);
- byte[] buf = new byte[1024];
- int len = 0;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- //读取数据
- while((len = fis.read(buf)) != -1){
- baos.write(buf, 0, len);
- }
- byte[] data = baos.toByteArray();
- //关闭流
- baos.close();
- fis.close();
- return new String(data);
- }
- }
package com.geniusxiaoyu.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.os.Environment;
public class FileService {
private Context context;
public FileService(Context context){
this.context = context;
}
/**
* 保存文件
* @param filename 文件名
* @param content 内容
* @param mode 模式
* @throws Exception
*/
public void save(String filename, String content, int mode) throws Exception{
FileOutputStream fos = context.openFileOutput(filename, mode);
//写入数据
fos.write(content.getBytes());
//关闭输出流
fos.close();
}
/**
* 保存文件,以私有模式保存
* @param filename 文件名
* @param content 内容
* @throws Exception
*/
public void save(String filename, String content) throws Exception{
save(filename, content, Context.MODE_PRIVATE);
}
/**
* 往存储卡中写入数据
* @param filename
* @param content
* @throws Exception
*/
public void saveToSDCard(String filename, String content) throws Exception{
//SDcard路径在2.2以前是/sdcard,在2.2以上版本中是/mnt/sdcard,最好采用下面的方式灵活获取,适用于所有版本
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos = new FileOutputStream(file);
//写入数据
fos.write(content.getBytes());
//关闭输出流
fos.close();
}
public String readFile(String filename) throws Throwable{
FileInputStream fis = context.openFileInput(filename);
byte[] buf = new byte[1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//读取数据
while((len = fis.read(buf)) != -1){
baos.write(buf, 0, len);
}
byte[] data = baos.toByteArray();
//关闭流
baos.close();
fis.close();
return new String(data);
}
}
src/com/geniusxiaoyu/file/FileActivity.java
- package com.geniusxiaoyu.file;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Environment;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- import com.geniusxiaoyu.service.FileService;
- public class FileActivity extends Activity {
- private FileService fileService;
- private static final String TAG = "FileActivity";
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- fileService = new FileService(this);
- Button button = (Button)this.findViewById(R.id.button);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- //1.获取输入的数据
- EditText filenameText = (EditText)findViewById(R.id.filename);
- EditText filecontentText = (EditText)findViewById(R.id.filecontent);
- String filename = filenameText.getText().toString();
- String filecontent = filecontentText.getText().toString();
- //2.保存内容
- try {
- //直接存入手机
- fileService.save(filename, filecontent);
- //判断手机上是否有SDCard,并且可以进行读写访问
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- fileService.saveToSDCard(filename, filecontent);
- Toast.makeText(FileActivity.this, R.string.success, Toast.LENGTH_LONG).show();
- }else{
- Toast.makeText(FileActivity.this, R.string.sdcarderror, Toast.LENGTH_LONG).show();
- }
- } catch (Exception e) {
- Log.e(TAG, e.toString());
- Toast.makeText(FileActivity.this, R.string.failed, Toast.LENGTH_LONG).show();
- }
- }
- });
- }
- }
package com.geniusxiaoyu.file;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.geniusxiaoyu.service.FileService;
public class FileActivity extends Activity {
private FileService fileService;
private static final String TAG = "FileActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fileService = new FileService(this);
Button button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//1.获取输入的数据
EditText filenameText = (EditText)findViewById(R.id.filename);
EditText filecontentText = (EditText)findViewById(R.id.filecontent);
String filename = filenameText.getText().toString();
String filecontent = filecontentText.getText().toString();
//2.保存内容
try {
//直接存入手机
fileService.save(filename, filecontent);
//判断手机上是否有SDCard,并且可以进行读写访问
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
fileService.saveToSDCard(filename, filecontent);
Toast.makeText(FileActivity.this, R.string.success, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(FileActivity.this, R.string.sdcarderror, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(TAG, e.toString());
Toast.makeText(FileActivity.this, R.string.failed, Toast.LENGTH_LONG).show();
}
}
});
}
}
单元测试类src/com/geniusxiaoyu/file/FileServiceTest.java
- package com.geniusxiaoyu.file;
- import android.content.Context;
- import android.test.AndroidTestCase;
- import android.util.Log;
- import com.geniusxiaoyu.service.FileService;
- public class FileServiceTest extends AndroidTestCase{
- private static final String TAG = "FileServiceTest";
- public void testSave() throws Throwable{
- FileService service = new FileService(this.getContext());
- service.save("test1.txt", "哈哈哈hahaha");
- }
- public void testReadFile() throws Throwable {
- FileService service = new FileService(this.getContext());
- String content = service.readFile("rwa.txt");
- //日志输出文件内容
- Log.i(TAG, content);
- }
- public void testSaveAppend() throws Throwable{
- FileService service = new FileService(this.getContext());
- service.save("test1.txt", "append something.", Context.MODE_APPEND);
- }
- public void testSaveReadable() throws Throwable{
- FileService service = new FileService(this.getContext());
- service.save("readable.txt", "I'm readable.", Context.MODE_WORLD_READABLE);
- }
- public void testSaveWriteable() throws Throwable{
- FileService service = new FileService(this.getContext());
- service.save("writeable.txt", "I'm writeable.", Context.MODE_WORLD_WRITEABLE);
- }
- public void testSaveRW() throws Throwable{
- FileService service = new FileService(this.getContext());
- service.save("rw.txt", "I'm readable & writeable.", Context.MODE_WORLD_WRITEABLE + Context.MODE_WORLD_READABLE);
- }
- public void testSaveRWA() throws Throwable{
- FileService service = new FileService(this.getContext());
- service.save("rwa.txt", "I'm readable & writeable & append.", Context.MODE_WORLD_WRITEABLE + Context.MODE_WORLD_READABLE + Context.MODE_APPEND);
- }
- }