openFlieOutput和openFileInput
Context提供了如下两个方法来打开本应用程序的数据文件夹里的I/O流
1.FileInputStream openFileInput(String name):打开应用程序的数据文件夹下的name文件对应输入流。
2.FileOutputStream openFileOutput(String name,int mede):打开应用程序的数据文件夹下的name文件
对应输出流。
上面的两个方法分别用于打开文件输入流、输出流,其中第二个方法的第二个参数指定打开文件的模式,该模式支持如下值:
1.MODE_PRIVATE:该文件只能被当前程序读写。
2.MODE_APPEND:以追加方式打开该文件,应用程序可以向该文件中追加内容。
3.MODE_WORLD_READABLE:该文件的内容可以被其他程序读取。
4.MODE_WORLD_WRITEABLE:该文件的内容可由其他程序读、写。
除此之外,Context还提供了如下介个方法来访问应用程序的数据文件夹。
1.getDir(String name,int mode):在应用程序的数据文件夹下获取或创建name对应的子目录。
2.File getFilesDir():获取该应用程序的数据文件夹的绝对路径。
3.String[] fileList():返回该应用程序的数据文件夹下的全部文件。
4.deleteFile(String):删除该应用程序的数据文件夹下的指定文件。
读写SD卡上的文件
读、写SD上的文件步骤:
1.调用Environment的getExternalStorageState()方法判断手机上是否插入了SD卡,并且应用程序具有读写SD
卡的权限。
//如果手机已经插入SD卡,且应用程序具有读写SD卡的能力,下面语句返回true
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
2.调用Environment的getExternalStorageDirectory()方法获取外部存储器,也就是SD卡的目录
3.使用FileInputStream、FileOutputStream、FileReader或FileWriter读、写SD卡里的文件。
publicclassSaveDataOnBextendsBaseActivity {
private EditText et_savedata;
private FileOutputStream outputStream;
private BufferedWriter writer;
private Button btn_send;
private TextView tv_showdata;
private Button btn_read;
private FileInputStream inputStream;
private StringBuffer content;
private BufferedReader reader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. savedata);
et_savedata = (EditText) findViewById(R.id.et_savedata );
btn_send = (Button) findViewById(R.id. btn_send);
btn_send.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
//获取到想要保存的数据
String data=et_savedata.getText().toString().trim();
Save(data);
}
});
tv_showdata = (TextView) findViewById(R.id.tv_showdata );
btn_read = (Button) findViewById(R.id. btn_read);
btn_read.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
String showd=Read();
tv_showdata.setText(showd);
}
});
}
private void Save(String data) {
try {
//声明FileOutputStream对象打开输出流(想要把数据保存到的文件名,写入模式覆盖或插入)
outputStream = openFileOutput( "data", MODE_PRIVATE);
//声明BufferedWriter对象写入流
writer = new BufferedWriter( new OutputStreamWriter(outputStream));
//写入数据
writer.write(data);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if( writer!= null){
writer.close();//关闭
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
private String Read() {
try {
//声明FileInputStream对象打开输入流获取文件内容
inputStream = openFileInput( "data");
reader = new BufferedReader( new InputStreamReader(inputStream));
content = new StringBuffer();
String readdata= "";
while ((readdata= reader.readLine())!= null) {
content.append(readdata);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if ( reader!= null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
}