Android文件存储和读取方式主要用到两个方法,第一个是文件写入方法OpenFileOutput();返回的是FileOutputStream对象,第二个是文件读取方法OpenFileInput();返回的是FileIntputStream对象。
文件写入方式:
- 1.首先通过OpenFileOutput()方法,这个方法传人两个参数,第一个参数是文件名,第二个参数是文件的操作模式,获得FileOutputSteam对象
FileOutputStream out = OpenFileOutput("content",Context.MODE_PRIVATE);
String data="Hello World!"
BufferWriter writer = new BufferWrite(new OutputStreamWriter(out));
writer.write(data);
文件读取方式:
- 1.首先通过OpenFileInput()方法,这个方法传入一个参数,文件名,获得FileInputStream对象
FileInputStream in = OpenFileInput("content");
BufferReader reader = new BufferReader(new inputStreamReader(in));
StringBuilder data = new StringBuilder();
String line;
while((line=reader.readLine())!=null){
data.append(line);
}
完整的Java代码
package com.example.kevin.filetest;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
private EditText write;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
write = (EditText) findViewById(R.id.write);
String inputText = load();
//TextUtils.isEmpty判断字符是否null或空字符,是的就返回true
if (!TextUtils.isEmpty(inputText)) {
write.setText(inputText);
write.setSelection(inputText.length());
Toast.makeText(getApplicationContext(), "读取结果返回成功", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
String data = write.getText().toString();
save(data);
}
//保存文件操作
private void save(String data) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("content", MODE_APPEND);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//读取文件操作
private String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("content");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
}
网友评论