1.文件(Files)
2.SharedPreferences
3.SQLite数据库
4.ContentProvider
5.网络
openFileOutPut方法的第二参数用于指定操作模式,四种模式:
SharedPrefrernces
···
package com.example.filetext;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
private Context mComtext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mComtext = MainActivity.this;
try {
FileOutputStream openFileOutput = mComtext.openFileOutput("111.txt", MODE_APPEND);
openFileOutput.write("123456!".getBytes());
openFileOutput.close();
//
FileInputStream openFileInput = mComtext.openFileInput("111.txt");
byte [] b=new byte[1024];
int read = openFileInput.read(b);
Log.e("TAG", "read----->"+new String(b,0,read));
} catch (Exception e) {
e.printStackTrace();
}
//获取file目录的路径
File filesDir = getFilesDir();//获取应用包名下的file目录
File cacheDir = getCacheDir();//获取应用包名下的cache目录
File ed = Environment.getExternalStorageDirectory();//SD卡路径
Log.e("TAG", filesDir.getPath());
Log.e("TAG", cacheDir.getPath());
Log.e("TAG", ed.getPath());
//使用SD卡之前先判断是否挂载
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File sd = Environment.getExternalStorageDirectory();
File file = new File(sd,"t12.txt");
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write("456".getBytes());
fos.close();
FileInputStream fis = new FileInputStream(file);
byte b[]= new byte [1024];
int read = fis.read(b);
Log.e("TAG", "------>"+new String(b,0,read));
} catch (IOException e) {
e.printStackTrace();
Log.d("sss",e.getMessage());
}
}
findViewById(R.id.btn1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//1.创建shareprefercens对象
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
//2.获取sp的编辑器
Editor edit = sp.edit();
//3.使用edit存储数据
edit.putString("name", "zhangsan");
edit.putInt("age", 18);
edit.putBoolean("sex", true);
//4.提交
edit.commit();
}
});
findViewById(R.id.btn2).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//1.创建shareprefercens对象
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
//2.获取数据
String string = sp.getString("name", "11");
Log.e("TAG", string);
}
});
}
}
···