---
title: "【Android】文件读写操作（含SDCard的读写）"
author: "ppjava"
date: "2012-09-12T16:03:11Z"
tags: []
categories: ["移动开发"]
slug: "android-sdcard"
draft: false
lastmod: "2012-09-12T16:03:11Z"
id: 1676924
url: "https://ppjava.iteye.com/blog/1676924"
---

[http://blog.csdn.net/kesenhoo/article/details/6531194](http://blog.csdn.net/kesenhoo/article/details/6531194)

 

**在AndroidManifest文件下添加SDCard的读写权限**

 

1. &lt;!-- 在SDCard中创建与删除文件权限 --&gt;
2. &lt;uses-permission android:name="android.permission.MOUNT\_UNMOUNT\_FILESYSTEMS"/&gt;
3. &lt;!-- 往SDCard写入数据权限 --&gt;
4. &lt;uses-permission android:name="android.permission.WRITE\_EXTERNAL\_STORAGE"/&gt;

 

 

**2.文件操作的各种模式如下代码：（注意通过getExternalStorageDirectory方法获取SDCard的文件路径）**

001. **package com.hoo.file;**
002. **import java.io.ByteArrayOutputStream;**
003. **import java.io.File;**
004. **import java.io.FileInputStream;**
005. **import java.io.FileOutputStream;**
006. **import android.content.Context;**
007. **import android.os.Environment;**
008. **public class FileService**
009. **{**
010. **private Context context;**
011. **public FileService(Context context)**
012. **{**
013. **this.context = context;**
014. **}**
015. **/\*\***
016. *** 读取文件的内容**
017. *** @param filename 文件名称**
018. *** @return**
019. *** @throws Exception**
020. **\*/**
021. **public String readFile(String filename) throws Exception**
022. **{**
023. **//获得输入流**
024. **FileInputStream inStream = context.openFileInput(filename);**
025. **//new一个缓冲区**
026. **byte\[] buffer = new byte\[1024];**
027. **int len = 0;**
028. **//使用ByteArrayOutputStream类来处理输出流**
029. **ByteArrayOutputStream outStream = new ByteArrayOutputStream();**
030. **while( (len = inStream.read(buffer))!= -1)**
031. **{**
032. **//写入数据**
033. **outStream.write(buffer, 0, len);**
034. **}**
035. **//得到文件的二进制数据**
036. **byte\[] data = outStream.toByteArray();**
037. **//关闭流**
038. **outStream.close();**
039. **inStream.close();**
040. **return new String(data);**
041. **}**
042. **/\*\***
043. *** 以默认私有方式保存文件内容至SDCard中**
044. *** @param filename**
045. *** @param content**
046. *** @throws Exception**
047. **\*/**
048. **public void saveToSDCard(String filename, String content) throws Exception**
049. **{**
050. **//通过getExternalStorageDirectory方法获取SDCard的文件路径**
051. **File file = new File(Environment.getExternalStorageDirectory(), filename);**
052. **//获取输出流**
053. **FileOutputStream outStream = new FileOutputStream(file);**
054. **outStream.write(content.getBytes());**
055. **outStream.close();**
056. **}**
057. **/\*\***
058. *** 以默认私有方式保存文件内容，存放在手机存储空间中**
059. *** @param filename**
060. *** @param content**
061. *** @throws Exception**
062. **\*/**
063. **public void save(String filename, String content) throws Exception**
064. **{**
065. **//**
066. **FileOutputStream outStream = context.openFileOutput(filename, Context.MODE\_PRIVATE);**
067. **outStream.write(content.getBytes());**
068. **outStream.close();**
069. **}**
070. **/\*\***
071. *** 以追加的方式保存文件内容**
072. *** @param filename 文件名称**
073. *** @param content 文件内容**
074. *** @throws Exception**
075. **\*/**
076. **public void saveAppend(String filename, String content) throws Exception**
077. **{**
078. **FileOutputStream outStream = context.openFileOutput(filename, Context.MODE\_APPEND);**
079. **outStream.write(content.getBytes());**
080. **outStream.close();**
081. **}**
082. **/\*\***
083. *** 以允许其他应用从该文件中读取内容的方式保存文件(Context.MODE\_WORLD\_READABLE)**
084. *** @param filename 文件名称**
085. *** @param content 文件内容**
086. *** @throws Exception**
087. **\*/**
088. **public void saveReadable(String filename, String content) throws Exception**
089. **{**
090. **FileOutputStream outStream = context.openFileOutput(filename, Context.MODE\_WORLD\_READABLE);**
091. **outStream.write(content.getBytes());**
092. **outStream.close();**
093. **}**
094. **/\*\***
095. *** 以允许其他应用往该文件写入内容的方式保存文件**
096. *** @param filename 文件名称**
097. *** @param content 文件内容**
098. *** @throws Exception**
099. **\*/**
100. **public void saveWriteable(String filename, String content) throws Exception**
101. **{**
102. **FileOutputStream outStream = context.openFileOutput(filename, Context.MODE\_WORLD\_WRITEABLE);**
103. **outStream.write(content.getBytes());**
104. **outStream.close();**
105. **}**
106. **/\*\***
107. *** 以允许其他应用对该文件读和写的方式保存文件(MODE\_WORLD\_READABLE与MODE\_WORLD\_WRITEABLE)**
108. *** @param filename 文件名称**
109. *** @param content 文件内容**
110. *** @throws Exception**
111. **\*/**
112. **public void saveRW(String filename, String content) throws Exception**
113. **{**
114. **FileOutputStream outStream = context.openFileOutput(filename,**
115. **Context.MODE\_WORLD\_READABLE + Context.MODE\_WORLD\_WRITEABLE);**
116. **//Context.MODE\_WORLD\_READABLE(1) + Context.MODE\_WORLD\_WRITEABLE(2),其实可用3替代**
117. **outStream.write(content.getBytes());**
118. **outStream.close();**
119. **}**
120. **}**

 

 

**3.写入数据前判断sdcard是否存在于手机上，是否有写保护**

01. **package com.hoo.file;**
02. **import android.app.Activity;**
03. **import android.os.Bundle;**
04. **import android.os.Environment;**
05. **import android.util.Log;**
06. **import android.view.View;**
07. **import android.widget.Button;**
08. **import android.widget.EditText;**
09. **import android.widget.Toast;**
10. **public class MainActivity extends Activity**
11. **{**
12. **private static final String TAG = "MainActivity";**
13. **private FileService fileService;**
14. **@Override**
15. **public void onCreate(Bundle savedInstanceState)**
16. **{**
17. **super.onCreate(savedInstanceState);**
18. **setContentView(R.layout.main);**
19. **fileService = new FileService(this);**
20. **//使用下面的方法可以快速获取当前文件夹的位置，**
21. **//这样可以在后面追加路径从而避免使用绝对路径**
22. **//File filedir = this.getFilesDir();**
23. **Button button = (Button) this.findViewById(R.id.button);**
24. **button.setOnClickListener(new View.OnClickListener()**
25. **{**
26. **@Override**
27. **public void onClick(View v)**
28. **{**
29. **//获取EditText中的内容**
30. **EditText filenameText = (EditText) findViewById(R.id.filename);**
31. **EditText contentText = (EditText) findViewById(R.id.filecontent);**
32. **String filename = filenameText.getText().toString();**
33. **String content = contentText.getText().toString();**
34. **try**
35. **{**
36. **//使用通常文件保存方式,默认保存在data/data/包名/file/XXX里面**
37. **//fileService.save(filename, content);**
38. **//判断sdcard是否存在于手机上而且没有写保护**
39. **//Android2.2版本以后sdcard的路径在mnt/sdcard，2.2之前在/sdcard**
40. **if(Environment.getExternalStorageState().equals(Environment.MEDIA\_MOUNTED))**
41. **{**
42. **//保存到SDCard中**
43. **fileService.saveToSDCard(filename, content);**
44. **//提示保存成功**
45. **Toast.makeText(MainActivity.this, R.string.success, 1).show();**
46. **}**
47. **else**
48. **{**
49. **//提示保存失败**
50. **Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();**
51. **}**
52. **}**
53. **catch (Exception e)**
54. **{**
55. **Log.e(TAG, e.toString());**
56. **Toast.makeText(MainActivity.this, R.string.error, 1).show();**
57. **}**
58. **}**
59. **});**
60. **}**
61. **}**