(1)使用Activity的openFileOutput()方法,存放些小文件还行。SDCard存放大文件,SDCard看做U盘或移动硬盘。
(2)注意:在程序中访问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"/>
(3) 要往SDCard存放文件,程序必须先判断手机是否装有SDCard,并且可以进行读写。
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File saveFile = new File(sdCardDir, “ljq.txt”);
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("abc".getBytes());
outStream.close();
}
Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,
(4)要获取SDCard的目录,你也可以这样写:
File sdCardDir = new File("/mnt/sdcard"); //获取SDCard目录
File saveFile = new File(sdCardDir, "ljq.txt");
//上面两句代码可以合成一句: File saveFile = new File("/mnt/sdcard/ljq.txt");
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("abc".getBytes());
outStream.close();
案例
main.xml布局文件
<?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"
>
<!-- 相对布局 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/filename"
android:id="@+id/filenameLable" />
<EditText android:layout_width="250px"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/filenameLable"
android:layout_alignTop="@id/filenameLable"
android:layout_marginLeft="10px"
android:text="ljq.txt"
android:id="@+id/filename" />
</RelativeLayout>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/content" />
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="3"
android:id="@+id/content" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/button"
android:layout_alignTop="@id/button"
android:layout_marginLeft="10px"
android:minLines="3"
android:text="@string/readButton"
android:id="@+id/readButton" />
</RelativeLayout>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView" />
</LinearLayout>
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 = " content " > 文件内容 </ string > < string name = " button " > 保存 </ string > < string name = " readButton " > 读取内容 </ string > < string name = " error " > 保存失败 </ string > < string name = " success " > 保存成功 </ string > </ resources >
FileService工具类
package com.ljq.service; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; public class FileService { /** * 保存数据 * * @param outputStream * @param content * @throws Exception */ public static void save(OutputStream outputStream, String content) throws Exception { outputStream.write(content.getBytes()); outputStream.close(); } /** * 读取数据 * * @param inputStream * @return * @throws Exception */ public static String read(InputStream inputStream) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 往内存写数据 byte [] buffer = new byte [ 1024 ]; // 缓冲区 int len = - 1 ; while ((len = inputStream.read(buffer)) != - 1 ) { byteArrayOutputStream.write(buffer, 0 , len); } byte [] data = byteArrayOutputStream.toByteArray(); // 存储数据 byteArrayOutputStream.close(); inputStream.close(); return new String(data); } }
SdcardActivity类
public class SdcardActivity extends Activity {
private final String TAG = "FileActivity";
private EditText filenameText;
private TextView resultView;
private EditText contentText;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
filenameText=(EditText)this.findViewById(R.id.filename);
contentText = (EditText)this.findViewById(R.id.content);
resultView = (TextView)this.findViewById(R.id.resultView);
Button saveButton = (Button)this.findViewById(R.id.saveButton);
saveButton.setOnClickListener(listener);
Button readButton = (Button)this.findViewById(R.id.readButton);
readButton.setOnClickListener(listener);
}
private View.OnClickListener listener=new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button button=(Button)v;
String filename=filenameText.getText().toString();
// Environment.getExternalStorageDirectory()等价于new File("/sdcard")---->获取sdcard目录
//File file = new File("/sdcard" + filename);
File file=new File(Environment.getExternalStorageDirectory(),filename);
switch(button.getId()){
case R.id.saveButton:
int resId = R.string.success;
String content=contentText.getText().toString();
if(Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)){
try{
FileOutputStream fileOutputStream=new FileOutputStream(file);
FileService.save(fileOutputStream, content);
}catch(Exception e){
Log.e(TAG, e.toString());
resId = R.string.error;
}
Toast.makeText(SdcardActivity.this, resId, Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(SdcardActivity.this, "sdcard不存在或写保护", Toast.LENGTH_LONG).show();
}
break;
case R.id.readButton:
try{
InputStream inputStream=new FileInputStream(file);
String result=FileService.read(inputStream);
resultView.setText(result);
}catch(Exception e){
Log.e(TAG, e.toString());
e.printStackTrace();
}
break;
}
}
};
}
清单文件
<? xml version="1.0" encoding="utf-8" ?> < manifest xmlns:android ="http://schemas.android.com/apk/res/android" package ="com.ljq.sdcard" android:versionCode ="1" android:versionName ="1.0" > < application android:icon ="@drawable/icon" android:label ="@string/app_name" > < activity android:name =".SdcardActivity" 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 ="7" /> <!-- 在SDCard中创建与删除文件权限 --> < uses-permission android:name ="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 往SDCard写入数据权限 --> < uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE" /> </ manifest >
运行结果