Android local data storage (2): File file storage

There are many ways to store data, such as database storage, SharedPreferences storage, file storage, etc.;

Here we will introduce the simplest file storage method;

The file storage is simply the IO stream in the general JAVASE, but it is only applied to the Android phone;

1. File storage core code

 

file storage

 

(1)FileOutputStream out = context.openFileOutput(String filename,int mode); Obtain the file output stream in mode mode

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

FileOutputStream out = null;  
out = context.openFileOutput(filename, Context.MODE_***);  
out.write(filecontent.getBytes("UTF-8"));  
out.close();

 Note: files are stored in /data/data/package/files by default;

 

 

file read

 

(1)FileInputStream in = context.openFileInput(String filename); Get the file stream of a file

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

/*
<span style="white-space:pre"> </span> Read a fixed byte each time, and output this byte to the byte output stream. output together
*/  
FileInputStream in = null;  
ByteArrayOutputStream bout = null;  
byte[]buf = new byte[1024];  
bout = new ByteArrayOutputStream();  
int length = 0;  
in = context.openFileInput(filename); //Get the input stream  
while((length=in.read(buf))!=-1){  
    bout.write(buf,0,length);  
}  
byte[] content = bout.toByteArray();  
filecontentEt.setText(new String(content,"UTF-8")); //Set the text box to read content  
in.close();  
bout.close();  

 Note: The file of /data/data/package/files will be read by default;

 

 

2. Introduction to file mode

 

1.Context.MODE_PRIVATE: private override mode - rw- rw- ---

Can only be accessed by the current application, and overwrites if written ;

2.Context.MODE_APPEND: private append mode - rw- rw- ---

Accessible only by the current application, and appends if written;

3. Context, MODE_WORLD_READABLE: public read-only mode - rw- rw- r--

can be read by other applications;

4.Context.MODE_WORLD_WRITEABLE: public writable mode - rw- rw- -w-

Can be written by other applications, but not read;

 

Note that if you want the other to make the file modes superimposed, you can use the plus sign to connect;

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

 

三、简单应用实例

 

1.效果图

 

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

 

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

 

 

MainActivity.java

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中设置:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>  

 存储到sdcard核心代码:

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

 读取sdcard核心代码:

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) The sdcard storage method cannot be used purely, because if it is impossible to determine whether a mobile phone has an sdcard, if not, other solutions need to be provided, such as

Save to phone storage;

Prompt that there is no sdcard;

can use:

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
    //Execute the storage sdcard method  
}  
else{  
    //Store to the phone, or prompt  
}  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326538824&siteId=291194637