Android入门:File文件存储

数据的存储有多种方式,比如数据库存储、SharedPreferences存储、文件存储等;

这里我们将要介绍最简单的文件存储方式;

文件存储简单的来说就是一般的JAVASE中的IO流,只是把他应用于Android手机中而已;


一、文件存储核心代码


文件存储


(1)FileOutputStream out = context.openFileOutput(String filename,int mode); 以mode模式获得文件输出流

(2)out.write(byte[]b);

  1. FileOutputStream out = null;  
  2. out = context.openFileOutput(filename, Context.MODE_***);  
  3. out.write(filecontent.getBytes("UTF-8"));  
  4. out.close();  
FileOutputStream out = null;
out = context.openFileOutput(filename, Context.MODE_***);
out.write(filecontent.getBytes("UTF-8"));
out.close();
注意:文件默认会存储到/data/data/package/files中;

文件读取


(1)FileInputStream in = context.openFileInput(String filename);   获得某个文件的文件流

(2)int length = in.read(byte[]);

  1. /* 
  2. <SPAN style="WHITE-SPACE: pre"> </SPAN>每次读取固定的字节,并将此字节输出到字节输出流中,当全部读取完毕后,将字节流中的内容一并输出 
  3. */  
  4. FileInputStream in = null;  
  5. ByteArrayOutputStream bout = null;  
  6. byte[]buf = new byte[1024];  
  7. bout = new ByteArrayOutputStream();  
  8. int length = 0;  
  9. in = context.openFileInput(filename); //获得输入流   
  10. while((length=in.read(buf))!=-1){  
  11.     bout.write(buf,0,length);  
  12. }  
  13. byte[] content = bout.toByteArray();  
  14. filecontentEt.setText(new String(content,"UTF-8")); //设置文本框为读取的内容   
  15. in.close();  
  16. bout.close();  
/*
	每次读取固定的字节,并将此字节输出到字节输出流中,当全部读取完毕后,将字节流中的内容一并输出
*/
FileInputStream in = null;
ByteArrayOutputStream bout = null;
byte[]buf = new byte[1024];
bout = new ByteArrayOutputStream();
int length = 0;
in = context.openFileInput(filename); //获得输入流
while((length=in.read(buf))!=-1){
	bout.write(buf,0,length);
}
byte[] content = bout.toByteArray();
filecontentEt.setText(new String(content,"UTF-8")); //设置文本框为读取的内容
in.close();
bout.close();

注意:默认会读取/data/data/package/files的文件;


二、文件模式介绍


1.Context.MODE_PRIVATE:私有覆盖模式    -  rw-  rw-  ---

只能被当前应用访问,并且如果写入,则覆盖

2.Context.MODE_APPEND:私有追加模式     -   rw-  rw-  ---

只能被当前应用访问,并且如果写入,则追加;

3.Context,MODE_WORLD_READABLE:公有只读模式      -  rw-  rw-   r--

可以被其他应用读取;

4.Context.MODE_WORLD_WRITEABLE:公有可写模式     - rw-   rw-  -w-

可以被其他应用写入,但不能读取;


注意,如果希望其他使得文件模式叠加,则可以使用加号连接;

比如:Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE 表示其他应用读写;


三、简单应用实例


1.效果图


目标:当点击保存时,将以特定的文件名称和特定的文件内容保存内容,点击读取时,将读取特定的文件的文件内容显示到文件内容文本框;



当点击保存之后,效果如下:




MainActivity.java

  1. package org.xiazdong.file;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7.   
  8. import android.app.Activity;  
  9. import android.content.Context;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15.   
  16. public class MainActivity extends Activity {  
  17.     private Button saveButton,readButton;  
  18.     private EditText filenameEt,filecontentEt;  
  19.     private Context context = this;  
  20.     private OnClickListener listener = new OnClickListener(){  
  21.         @Override  
  22.         public void onClick(View v) {  
  23.             if(v==saveButton){  
  24.                 String filename = filenameEt.getText().toString();  
  25.                 String filecontent = filecontentEt.getText().toString();  
  26.                 FileOutputStream out = null;  
  27.                 try {  
  28.                     out = context.openFileOutput(filename, Context.MODE_PRIVATE);  
  29.                     out.write(filecontent.getBytes("UTF-8"));  
  30.                 } catch (Exception e) {  
  31.                     e.printStackTrace();  
  32.                 }  
  33.                 finally{  
  34.                     try {  
  35.                         out.close();  
  36.                     } catch (Exception e) {  
  37.                         e.printStackTrace();  
  38.                     }  
  39.                 }  
  40.             }  
  41.             else if(v==readButton){  
  42.                 String filename = filenameEt.getText().toString(); //获得读取的文件的名称   
  43.                 FileInputStream in = null;  
  44.                 ByteArrayOutputStream bout = null;  
  45.                 byte[]buf = new byte[1024];  
  46.                 bout = new ByteArrayOutputStream();  
  47.                 int length = 0;  
  48.                 try {  
  49.                     in = context.openFileInput(filename); //获得输入流   
  50.                     while((length=in.read(buf))!=-1){  
  51.                         bout.write(buf,0,length);  
  52.                     }  
  53.                     byte[] content = bout.toByteArray();  
  54.                     filecontentEt.setText(new String(content,"UTF-8")); //设置文本框为读取的内容   
  55.                 } catch (Exception e) {  
  56.                     e.printStackTrace();  
  57.                 }  
  58.                 filecontentEt.invalidate(); //刷新屏幕   
  59.                 try{  
  60.                     in.close();  
  61.                     bout.close();  
  62.                 }  
  63.                 catch(Exception e){}  
  64.             }  
  65.         }  
  66.           
  67.     };  
  68.     @Override  
  69.     public void onCreate(Bundle savedInstanceState) {  
  70.         super.onCreate(savedInstanceState);  
  71.         setContentView(R.layout.main);  
  72.         saveButton = (Button)this.findViewById(R.id.saveButton);  
  73.         readButton = (Button)this.findViewById(R.id.readButton);  
  74.         filenameEt = (EditText)this.findViewById(R.id.filename);  
  75.         filecontentEt = (EditText)this.findViewById(R.id.filecontent);  
  76.         saveButton.setOnClickListener(listener);  
  77.         readButton.setOnClickListener(listener);  
  78.     }  
  79. }  
package org.xiazdong.file;

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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	private Button saveButton,readButton;
	private EditText filenameEt,filecontentEt;
	private Context context = this;
	private OnClickListener listener = new OnClickListener(){
		@Override
		public void onClick(View v) {
			if(v==saveButton){
				String filename = filenameEt.getText().toString();
				String filecontent = filecontentEt.getText().toString();
				FileOutputStream out = null;
				try {
					out = context.openFileOutput(filename, Context.MODE_PRIVATE);
					out.write(filecontent.getBytes("UTF-8"));
				} catch (Exception e) {
					e.printStackTrace();
				}
				finally{
					try {
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			else if(v==readButton){
				String filename = filenameEt.getText().toString(); //获得读取的文件的名称
				FileInputStream in = null;
				ByteArrayOutputStream bout = null;
				byte[]buf = new byte[1024];
				bout = new ByteArrayOutputStream();
				int length = 0;
				try {
					in = context.openFileInput(filename); //获得输入流
					while((length=in.read(buf))!=-1){
						bout.write(buf,0,length);
					}
					byte[] content = bout.toByteArray();
					filecontentEt.setText(new String(content,"UTF-8")); //设置文本框为读取的内容
				} catch (Exception e) {
					e.printStackTrace();
				}
				filecontentEt.invalidate(); //刷新屏幕
				try{
					in.close();
					bout.close();
				}
				catch(Exception e){}
			}
		}
		
	};
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        saveButton = (Button)this.findViewById(R.id.saveButton);
        readButton = (Button)this.findViewById(R.id.readButton);
        filenameEt = (EditText)this.findViewById(R.id.filename);
        filecontentEt = (EditText)this.findViewById(R.id.filecontent);
        saveButton.setOnClickListener(listener);
        readButton.setOnClickListener(listener);
    }
}


四、将文件保存到SDCard


如果一个文件很大,则不适用于存放在手机的存储中;

如果手机存在sdcard,则sdcard的目录为/mnt/sdcard目录;


步骤1:设置模拟器支持sdcard





此时模拟器已经支持sdcard了;


步骤2:在应用中设置权限


在AndroidManifest.xml中设置:

  1. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>  
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>  
  3.    <application.../>  
	<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <application.../>


存储到sdcard核心代码:

  1. File f = new File(Environment.getExternalStorageDirectory(),filename);  
  2. out = new FileOutputStream(f,true);  
  3. out.write(filecontent.getBytes("UTF-8"));  
File f = new File(Environment.getExternalStorageDirectory(),filename);
out = new FileOutputStream(f,true);
out.write(filecontent.getBytes("UTF-8"));

读取sdcard核心代码:

  1. File f = new File(Environment.getExternalStorageDirectory(),filename);  
  2. in = new FileInputStream(f);  
  3. while((length=in.read(buf))!=-1){  
  4.     bout.write(buf,0,length);  
  5. }  
  6. byte[] content = bout.toByteArray();  
File f = new File(Environment.getExternalStorageDirectory(),filename);
in = new FileInputStream(f);
while((length=in.read(buf))!=-1){
	bout.write(buf,0,length);
}
byte[] content = bout.toByteArray();

其实主要就是存储目录问题;


注意:


在Android中1.5、1.6的sdcard目录为/sdcard,而Android2.0以上都是/mnt/sdcard,因此如果我们在保存时直接写具体目录会不妥,因此我们可以使用:

Environment.getExternalStorageDirectory();获取sdcard目录;


建议:


(1)不能纯粹使用sdcard保存法,因为如果不能判定一部手机是否存在sdcard,如果没有,则需要提供其他解决方法,比如

保存到手机存储;

提示不存在sdcard;

可以使用:

  1. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
  2.     //执行存储sdcard方法   
  3. }  
  4. else{  
  5.     //存储到手机中,或提示   
  6. }  
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
	//执行存储sdcard方法
}
else{
	//存储到手机中,或提示
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值