Android存储 - SD卡或者文件存储实现。

jopen 12年前

Android实现SD卡和实现内存文件存储的做法基本是一样的。只是取得文件路径的方法不一样,基本上跟java的文件操作是一致的,下面是程序的代码。配置取的位置和实现有所不同,其他是一样的,下面是代码:

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">        <EditText android:id="@+id/edit1"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:lines="4"/>        <Button android:id="@+id/write"            android:layout_width="wrap_content"            android:layout_height="wrap_content"             android:text="@string/write"/>        <EditText android:id="@+id/edit2"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:editable="false"            android:cursorVisible="false"            android:lines="4"/>              <Button android:id="@+id/read"            android:layout_width="wrap_content"            android:layout_height="wrap_content"             android:text="@string/read"/>        </LinearLayout>  
在AndroidManifest清单文件中要对SD卡读取进行支持。代码如下:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
在String.xml中添加两个内容:
    <string name="read">读取</string>        lt;string name="write">写入</string>   
下面是文件实现的代码:
package cn.jason.io;    import java.io.FileInputStream;  import java.io.FileOutputStream;  import java.io.IOException;  import java.io.PrintStream;    import android.app.Activity;  import android.os.Bundle;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  import android.widget.EditText;    public class FileTestActivity extends Activity {      final String FILE = "jason.bin";         @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);                    Button read = (Button) findViewById(R.id.read);          Button write = (Button) findViewById(R.id.write);                    final EditText edit1 = (EditText) findViewById(R.id.edit1);          final EditText edit2 = (EditText) findViewById(R.id.edit2);                              write.setOnClickListener(new OnClickListener() {          @Override     public void onClick(View v) {      write(edit1.getText().toString());      edit1.setText("");     }    });                    read.setOnClickListener(new OnClickListener() {          @Override     public void onClick(View v) {      edit2.setText(read());     }    });      }               private String read() {    try {     FileInputStream fis = openFileInput(FILE);     byte[] buffer = new byte[1024];     int hasRead = 0;     StringBuilder sb = new StringBuilder("");     while ((hasRead = fis.read(buffer)) > 0) {      sb.append(new String(buffer, 0, hasRead));     }     return sb.toString();    } catch (IOException e) {     e.printStackTrace();    }    return null;   }      private void write(String content)   {    try    {     // 以追加模式打开文件输出流     FileOutputStream fos = openFileOutput(FILE, MODE_APPEND);     // 将FileOutputStream包装成PrintStream     PrintStream ps = new PrintStream(fos);     // 输出文件内容     ps.println(content);     ps.close();    }    catch (Exception e)    {     e.printStackTrace();    }   }  }

下面是sd卡存储实现的代码:

package cn.jason.io;    import java.io.BufferedReader;  import java.io.File;  import java.io.FileInputStream;  import java.io.FileNotFoundException;  import java.io.IOException;  import java.io.InputStreamReader;  import java.io.RandomAccessFile;  import java.net.ContentHandler;    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;    public class SDCardTestActivity extends Activity {      final String FILE = "/jason.bin";      @Override   public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);        Button read = (Button) findViewById(R.id.read);    Button write = (Button) findViewById(R.id.write);    // 获取两个文本框    final EditText edit1 = (EditText) findViewById(R.id.edit1);    final EditText edit2 = (EditText) findViewById(R.id.edit2);    // 为write按钮绑定事件监听器    write.setOnClickListener(new OnClickListener() {     @Override     public void onClick(View source) {      // 将edit1中的内容写入文件中      write(edit1.getText().toString());      edit1.setText("");     }    });        read.setOnClickListener(new OnClickListener() {     @Override     public void onClick(View v) {      // 读取指定文件中的内容,并显示出来      edit2.setText(read());     }    });   }      private String read() {    // 如果手机插入了SD卡,而且应用程序具有访问SD的权限        try {     if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {      // 获取SD卡的目录      File sdDirFile = Environment.getExternalStorageDirectory();      //获取指定文件对应的输入流      FileInputStream fis = new FileInputStream(sdDirFile.getCanonicalPath()+ FILE);      //将指定输入流包装成BufferedReader      BufferedReader br = new BufferedReader(new InputStreamReader(fis));            StringBuilder sb = new StringBuilder("");      String line = null;      while ((line =br.readLine())!=null) {       sb.append(line);                  }      return sb.toString();     }    } catch (FileNotFoundException e) {     e.printStackTrace();    } catch (IOException e) {     e.printStackTrace();    }    return null;   }     private void write(String context){    try {           if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){            File sdDir = Environment.getExternalStorageDirectory();            File targetFile = new File(sdDir.getCanonicalPath()+ FILE);            RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");            raf.seek(targetFile.length());            raf.write(context.getBytes());            raf.close();           }          } catch (Exception e) {          }   }  }
转自:http://blog.csdn.net/jasonchris/article/details/7619468