android 数据存储之 读写文件

在android中当然也可以通过读写文件来保存数据,以下例子中的文件存放的位置在\data\data\PROJ_NAME\files\  下面

MODE_PRIVATE是默认的属性,表示只有当前的app可以使用,当然还有其他的属性可以查看手册

如果只有MODE_PRIVATE的话,如果文件已经存在,那写入的新数据会把原有的数据覆盖掉。

如果想在原有的文件后面追加数据,那应该用MODE_PRIVATE|MODE_APPEND属性。

package MySharePerferences.code;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    
    private Button button;
    private Button button1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                
        
        button = (Button)findViewById(R.id.btn);
        button1 = (Button)findViewById(R.id.btn1);
        
        button1.setOnClickListener( new Button.OnClickListener()
        {
            @Override
            public void onClick(View v )
            {
                try
                {                    
                    FileInputStream fin = openFileInput("test.txt");
                    int len = fin.available();
                    String str;
                    byte[] buff = new byte[len];
                    fin.read(buff);
                    str = EncodingUtils.getString(buff,"UTF-8");
                    fin.close();
                    
                    Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
                }
                catch(Exception e )
                {
                    
                }
                
            }
        }
        );
        
        
        button.setOnClickListener( new Button.OnClickListener()
        {
            @Override
            public void onClick(View v )
            {                
                try
                {
                    String str = "so what?";
                    FileOutputStream fout = openFileOutput("test.txt",MODE_PRIVATE);
                    byte[] bytes = str.getBytes();
                    fout.write(bytes);
                    fout.close();
                }
                catch(Exception e )
                {
                    e.printStackTrace();
                }
            }
        }
        );
        
    }
}

原文地址:https://www.cnblogs.com/rollrock/p/2384296.html