---
title: "Android之怎么操作文件(读写以及保存到sdcard)"
author: "wangbobe"
date: "2012-08-26T10:20:12Z"
tags: []
categories: ["移动开发"]
slug: "android-sdcard"
draft: false
lastmod: "2012-08-26T10:20:12Z"
id: 1663090
url: "https://wangbobe.iteye.com/blog/1663090"
---

## 步骤如下：

 

一、介绍：

       此主要是介绍怎么把文件写入到手机存储上、怎么从手机存储上读取文件内容以及怎么把文件写到SDCard

二、新建一个android工程——FileOperate

       目录如下：

![](http://hiphotos.baidu.com/yuzhongxingke8/pic/item/35a610ec76c6a7ef974d7f87fdfaaf51f2de6667.jpg)

三、清单列表AndroidManifest.xml的配置为：

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;manifest xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
    package="com.example.files"  
    android:versionCode="1"  
    android:versionName="1.0" &gt;

    &lt;uses-sdk android:minSdkVersion="8" /&gt;

    &lt;application  
        android:icon="@drawable/ic\_launcher"  
        android:label="@string/app\_name" &gt;  
          
        &lt;!--单元测试 加这句--&gt;  
        &lt;uses-library android:name="android.test.runner" /&gt;  
          
        &lt;activity  
            android:name=".FileActivity"  
            android:label="@string/app\_name" &gt;  
            &lt;intent-filter&gt;  
                &lt;action android:name="android.intent.action.MAIN" /&gt;

                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;  
            &lt;/intent-filter&gt;  
        &lt;/activity&gt;  
    &lt;/application&gt;  
   &lt;!-- 往SDCard的创建与删除文件权限 --&gt;  
    &lt;uses-permission android:name="android.permission.MOUNT\_UNMOUNT\_FILESYSTEMS"/&gt;  
    &lt;!-- 往SDCard写入数据权限 --&gt;  
    &lt;uses-permission android:name="android.permission.WRITE\_EXTERNAL\_STORAGE"/&gt;  
      
      
    &lt;!--单元测试加这句，其中android:targetPackage为当前应用的包名  
    android:targetPackage 目标包是指单元测试的类的上面包和manifest的   
    package="com.example.main" 保持一致       
          这样就决定了你建立测试类的时候也必须在这个包下面  
    --&gt;  
 &lt;instrumentation android:name="android.test.InstrumentationTestRunner"  
 android:targetPackage="com.example.files"  
 android:label="Test for my app"/&gt;  
      
      
&lt;/manifest&gt;

 

四、FileActivity.java源码：

package com.example.files;

import java.io.FileNotFoundException;  
import java.io.IOException;

import com.example.service.FileService;

import android.app.Activity;  
import android.os.Bundle;  
import android.os.Environment;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.Toast;

public class FileActivity extends Activity {  
   
 EditText fileName ;  
 EditText fileContent;  
 Button fileSave;  
 OnClickListener fileSaveListener;  
 OnClickListener fileSaveSDListener;  
   
    /\** Called when the activity is first created. \*/  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
        fileSaveListener = new OnClickListener(){

   @Override  
   public void onClick(View v) {  
    //setTitle("123");  
    //Toast.makeText(FileActivity.this, "123", Toast.LENGTH\_LONG).show();  
    String fileNameStr = fileName.getText().toString();  
    String fileContentStr = fileContent.getText().toString();  
      
    FileService fileService = new FileService(getApplicationContext());  
    try {  
     fileService.save(fileNameStr,fileContentStr);  
     Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH\_LONG).show();  
    } catch (FileNotFoundException e) {  
     Toast.makeText(getApplicationContext(), R.string.failure, Toast.LENGTH\_LONG).show();  
     e.printStackTrace();  
    } catch (IOException e) {  
     // TODO Auto-generated catch block  
     e.printStackTrace();  
    }  
      
      
   }  
           
        };  
          
        fileSaveSDListener = new OnClickListener(){

   @Override  
   public void onClick(View v) {  
    //setTitle("123");  
    //Toast.makeText(FileActivity.this, "123", Toast.LENGTH\_LONG).show();  
    String fileNameStr = fileName.getText().toString();  
    String fileContentStr = fileContent.getText().toString();  
      
    FileService fileService = new FileService(getApplicationContext());  
    try {  
     //判断SDCard是否存在并且可以读写  
     if(Environment.getExternalStorageState().equals(Environment.MEDIA\_MOUNTED)){  
      fileService.saveToSD(fileNameStr,fileContentStr);  
      Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH\_LONG).show();  
     }   
     else  
     {  
      Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH\_LONG).show();  
     }  
       
    } catch (FileNotFoundException e) {  
     Toast.makeText(getApplicationContext(), R.string.sdcardfail, Toast.LENGTH\_LONG).show();  
     e.printStackTrace();  
    } catch (IOException e) {  
     // TODO Auto-generated catch block  
     e.printStackTrace();  
    }  
      
      
   }  
           
        };  
          
        Button fileSave = (Button) this.findViewById(R.id.fileSave);  
        fileSave.setOnClickListener(fileSaveListener);  
          
        Button fileSaveSD = (Button) this.findViewById(R.id.fileSaveSD);  
        fileSaveSD.setOnClickListener(fileSaveSDListener);  
          
        fileName = (EditText) this.findViewById(R.id.fileName);  
        fileContent = (EditText) this.findViewById(R.id.fileContent);  
          
          
          
    }  
}

五、FileService.java源码：

package com.example.service;

import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;

import android.content.Context;  
import android.os.Environment;

public class FileService {  
   
 private Context context;

 public FileService(Context context) {  
  super();  
  this.context = context;  
 }  
 /\**  
  * 写入文件到SD卡  
  * @throws IOException   
  \*/  
 public void saveToSD(String fileNameStr, String fileContentStr) throws IOException{  
    
  //备注:Java File类能够创建文件或者文件夹，但是不能两个一起创建  
  File file = new File("/mnt/sdcard/myfiles");  
//  if(!file.exists())  
//  {  
//   file.mkdirs();  
//  }  
//   File sd=Environment.getExternalStorageDirectory();   
//      String path=sd.getPath()+"/myfiles";   
//      File file=new File(path);   
//      if(file.exists()){   
//          file.delete();   
//      }  
      if(!file.exists()){  
       file.mkdir();  
      }  
      File file1 = new File(file, fileNameStr);

  FileOutputStream fos = new FileOutputStream(file1);  
  fos.write(fileContentStr.getBytes());  
  fos.close();  
 }

 /\**  
  * 保存文件到手机  
  * @param fileNameStr 文件名  
  * @param fileContentStr 文件内容  
  * @throws IOException   
  \*/  
 public void save(String fileNameStr, String fileContentStr) throws IOException {  
  //私有操作模式：创建出来的文件只能被本应用访问，其它应用无法访问该文件，另外采用私有操作模式创建的文件，写入文件中的内容会覆盖原文件的内容  
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE\_PRIVATE);  
  fos.write(fileContentStr.getBytes());  
  fos.close();  
 }  
   
 public void saveAppend(String fileNameStr, String fileContentStr) throws IOException {  
  //追加操作模式:不覆盖源文件，但是同样其它应用无法访问该文件  
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE\_APPEND);  
  fos.write(fileContentStr.getBytes());  
  fos.close();  
 }  
   
 public void saveReadable(String fileNameStr, String fileContentStr) throws IOException {  
  //读取操作模式:可以被其它应用读取，但不能写入  
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE\_WORLD\_READABLE);  
  fos.write(fileContentStr.getBytes());  
  fos.close();  
 }  
   
 public void saveWriteable(String fileNameStr, String fileContentStr) throws IOException {  
  //写入操作模式:可以被其它应用写入，但不能读取  
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE\_WORLD\_WRITEABLE);  
  fos.write(fileContentStr.getBytes());  
  fos.close();  
 }  
   
 public void saveReadWriteable(String fileNameStr, String fileContentStr) throws IOException {  
  //读写操作模式:可以被其它应用读写  
  FileOutputStream fos = context.openFileOutput(fileNameStr,   
    context.MODE\_WORLD\_READABLE+context.MODE\_WORLD\_WRITEABLE);  
  fos.write(fileContentStr.getBytes());  
  fos.close();  
 }  
   
   
 /\**  
  * 读取文件内容  
  * @param fileNamestr 文件名  
  * @return  
  * @throws IOException  
  \*/  
 public String read(String fileNamestr) throws IOException  
 {  
  FileInputStream fis = context.openFileInput(fileNamestr);  
  ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  byte\[] buffer = new byte\[1024];  
  int len = 0;  
  while((len = fis.read(buffer)) != -1){  
   bos.write(buffer,0,len);  
  }  
  byte\[] data = bos.toByteArray();  
    
    
  return new String(data);  
 }

}

六、FileServiceTest.java源码：

package com.junit.test;

import com.example.service.FileService;

import android.test.AndroidTestCase;  
import android.util.Log;

public class FileServiceTest extends AndroidTestCase {  
     /\**  
      * 测试私有模式的读取  
      * @throws Exception  
      \*/  
        public void testRead() throws Exception{  
         FileService fileService = new FileService(this.getContext());  
         String fileContext = fileService.read("fileSave.txt");  
         Log.i("FileRead", fileContext);  
        }  
        /\**  
         * 测试追加模式的写入  
         * @throws Exception  
         \*/  
        public void testSaveAppend() throws Exception{  
         FileService fileService = new FileService(this.getContext());  
         fileService.saveAppend("fileAppendSave.txt", "你好");  
        }  
        /\**  
         * 测试读取模式的读取  
         * @throws Exception  
         \*/  
        public void testSaveReadable() throws Exception{  
         FileService fileService = new FileService(this.getContext());  
         fileService.saveReadable("fileSaveReadable.txt", "wonengbeiduquma");  
        }  
        /\**  
         * 测试写入模式的写入  
         * @throws Exception  
         \*/  
        public void testSaveWriteable() throws Exception{  
         FileService fileService = new FileService(this.getContext());  
         fileService.saveWriteable("fileSaveWriteable.txt", "wonengbeiduquma");  
        }  
        /\**  
         * 测试读写模式的写入  
         * @throws Exception  
         \*/  
        public void testSaveReadWriteable() throws Exception{  
         FileService fileService = new FileService(this.getContext());  
         fileService.saveReadWriteable("fileSaveReadWriteable.txt", "我能被读写吗？");  
        }  
          
}

七、main.xml配置：

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;LinearLayout xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
    android:layout\_width="fill\_parent"  
    android:layout\_height="fill\_parent"  
    android:orientation="vertical" &gt;

    &lt;TextView  
        android:layout\_width="fill\_parent"  
        android:layout\_height="wrap\_content"  
        android:text="@string/file\_name" /&gt;

    &lt;EditText  
        android:id="@+id/fileName"  
        android:layout\_width="match\_parent"  
        android:layout\_height="wrap\_content" &gt;

        &lt;requestFocus /&gt;  
    &lt;/EditText&gt;

    &lt;TextView  
        android:id="@+id/textView1"  
        android:layout\_width="fill\_parent"  
        android:layout\_height="wrap\_content"  
        android:text="@string/file\_content" /&gt;

    &lt;EditText  
        android:id="@+id/fileContent"  
        android:layout\_width="match\_parent"  
        android:layout\_height="wrap\_content" android:minLines="5"/&gt;

    &lt;Button  
        android:id="@+id/fileSave"  
        android:layout\_width="wrap\_content"  
        android:layout\_height="wrap\_content"  
        android:text="@string/file\_save" /&gt;

    &lt;Button  
        android:id="@+id/fileSaveSD"  
        android:layout\_width="wrap\_content"  
        android:layout\_height="wrap\_content"  
        android:text="@string/file\_save\_sd" /&gt;

&lt;/LinearLayout&gt;

八、string.xml配置：

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;resources&gt;

    &lt;string name="hello"&gt;Hello World, FileActivity!&lt;/string&gt;  
    &lt;string name="app\_name"&gt;ExampleFileOperate&lt;/string&gt;  
    &lt;string name="file\_name"&gt;文件名称&lt;/string&gt;  
    &lt;string name="file\_content"&gt;文件内容&lt;/string&gt;  
    &lt;string name="file\_save"&gt;文件保存到手机&lt;/string&gt;  
    &lt;string name="file\_save\_sd"&gt;文件保存到SD卡&lt;/string&gt;  
    &lt;string name="success"&gt;保存完成&lt;/string&gt;  
    &lt;string name="failure"&gt;保存失败&lt;/string&gt;  
    &lt;string name="sdcardfail"&gt;sdCard不存在或者写保护&lt;/string&gt;  
&lt;/resources&gt;

九、运行为：

![](http://hiphotos.baidu.com/yuzhongxingke8/pic/item/61ae6bc7b74543a949bc2d6d1e178a82b8011423.jpg)

十、可以在另一个项目中增加测试类来测试其它应用是否可以读写这些模式下创建的文件：如FileServiceTest .java:

package com.example.junit;

import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;

import android.test.AndroidTestCase;  
import android.util.Log;

public class FileServiceTest extends AndroidTestCase {  
    /\**  
     * 私用，只能本应用读写，  
     * @throws Exception  
     \*/  
 public void testAccessPrivateFile() throws Exception{  
  String path = "/data/data/com.example.files/files/fileSave.txt";  
  File file = new File(path);  
  FileInputStream fis = new FileInputStream(file);  
    
  ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  byte\[] buffer = new byte\[1024];  
    
  int len = 0;  
  while((len = fis.read(buffer))!=-1)  
  {  
   bos.write(buffer,0,len);  
  }  
    
  byte\[] data = bos.toByteArray();  
  bos.close();  
  fis.close();  
    
  String content = new String(data);  
    
  Log.i("FileServiceTest",content);  
 }  
 /\**  
  * 私用  不覆盖文件，可以在文件后面追加内容  
  * @throws Exception  
  \*/  
 public void testAccessAppendFile() throws Exception{  
  String path = "/data/data/com.example.files/files/fileAppendSave.txt";  
  File file = new File(path);  
  FileInputStream fis = new FileInputStream(file);  
    
  ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  byte\[] buffer = new byte\[1024];  
    
  int len = 0;  
  while((len = fis.read(buffer))!=-1)  
  {  
   bos.write(buffer,0,len);  
  }  
    
  byte\[] data = bos.toByteArray();  
  bos.close();  
  fis.close();  
    
  String content = new String(data);  
    
  Log.i("FileServiceTest",content);  
 }  
 /\**  
  * 被其他应用程序读取，不能写入  
  * @throws Exception  
  \*/  
 public void testAccessReadableFile() throws Exception{  
  String path = "/data/data/com.example.files/files/fileSaveReadable.txt";  
  File file = new File(path);  
  FileInputStream fis = new FileInputStream(file);  
    
  ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  byte\[] buffer = new byte\[1024];  
    
  int len = 0;  
  while((len = fis.read(buffer))!=-1)  
  {  
   bos.write(buffer,0,len);  
  }  
    
  byte\[] data = bos.toByteArray();  
  bos.close();  
  fis.close();  
    
  String content = new String(data);  
    
  Log.i("FileServiceTest",content);  
 }  
   
 /\**  
  * 被其他应用程序写入，不能读取  
  * @throws Exception  
  \*/  
 public void testAccessWriteableFileRead() throws Exception{  
  String path = "/data/data/com.example.files/files/fileSaveWriteable.txt";  
  File file = new File(path);  
  FileInputStream fis = new FileInputStream(file);  
    
  ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  byte\[] buffer = new byte\[1024];  
    
  int len = 0;  
  while((len = fis.read(buffer))!=-1)  
  {  
   bos.write(buffer,0,len);  
  }  
    
  byte\[] data = bos.toByteArray();  
  bos.close();  
  fis.close();  
    
  String content = new String(data);  
    
  Log.i("FileServiceTest",content);  
 }  
 /\**  
  * 被其他应用程序写入，不能读取  
  * @throws Exception  
  \*/  
 public void testAccessWriteableFileWrite() throws Exception{  
  String path = "/data/data/com.example.files/files/fileSaveWriteable.txt";  
  File file = new File(path);  
  FileOutputStream fos = new FileOutputStream(file,true);//第二个参数为是否要追加内容还是覆盖内容，ture为追加，false为覆盖  
  fos.write("nihaoya".getBytes());  
    
  fos.close();  
    
 }  
   
   
 /\**  
  * 被其他应用程序可以读写  
  * @throws Exception  
  \*/  
 public void testAccessReadWriteableFileRead() throws Exception{  
  String path = "/data/data/com.example.files/files/fileSaveReadWriteable.txt";  
  File file = new File(path);  
  FileInputStream fis = new FileInputStream(file);  
    
  ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  byte\[] buffer = new byte\[1024];  
    
  int len = 0;  
  while((len = fis.read(buffer))!=-1)  
  {  
   bos.write(buffer,0,len);  
  }  
    
  byte\[] data = bos.toByteArray();  
  bos.close();  
  fis.close();  
    
  String content = new String(data);  
    
  Log.i("FileServiceTest",content);  
 }  
 /\**  
  * 被其他应用程序可以读写  
  * @throws Exception  
  \*/  
 public void testAccessReadWriteableFileWrite() throws Exception{  
  String path = "/data/data/com.example.files/files/fileSaveReadWriteable.txt";  
  File file = new File(path);  
  //此写入方法append=true时为追加模式，可以不对原文件进行覆盖  
  FileOutputStream fos = new FileOutputStream(file,true);  
  fos.write("恭喜你，你能加我啦！".getBytes());  
    
  fos.close();  
    
 }  
}

十一、注意事项：

        1、要在sdcard创建和删除以及写入数据必须添加下面两个权限：

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

       2、往sdcard上写入数据是可以先判断是否有此权限：

              //判断SDCard是否存在并且可以读写

             Environment.getExternalStorageState().equals(Environment.MEDIA\_MOUNTED

        3、在sdcard上创建文件夹的方法(推荐后面一种方法)：

            File file = new File("/mnt/sdcard/myfiles");

            if(!file.exists()){  
                 file.mkdir();  
            }

            或者

            File sd=Environment.getExternalStorageDirectory();   
            String path=sd.getPath()+"/myfiles";   
            File file=new File(path);   
            if(!file.exists()){  
               file.mkdir();  
            }

          4、多熟悉输入输出流的灵活应用

更多详细信息请查看[java教程网](http://www.itchm.com) [http://www.itchm.com/forum-59-1.html](http://www.itchm.com/forum-59-1.html)