- 文件存储
文件存储
所有的文件会默认存储在/data/data/<packagename>/files/目录下
openFileOutput('data',Context.MODE_PRIVATE) //该方法返回一个FileOutputStream
| 参数 | 作用 |
|---|---|
| Context.MODE_PRIVATE | 会覆盖原文件 |
| Context.PRIVATE | 在原有文件上追加 |
举例
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="存储"
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
final EditText editText = findViewById(R.id.edit_text);
final TextView textView = findViewById(R.id.text_view);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editText.getText() != null){
save("data",editText.getText().toString()); //将文件存储
textView.setText(load("data")); //取出文件
}
}
});
}
//文件存储
public void save(String fileName,String data){
FileOutputStream out = null;
BufferedWriter writer = null;
try{
out = openFileOutput(fileName, Context.MODE_PRIVATE);
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();
}
}
}
//文件读取
public String load(String fileName){
FileInputStream in = null;
BufferedReader reader = null;
StringBuffer content = new StringBuffer();
try{
in = openFileInput(fileName);
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null){
content.append(line);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return content.toString();
}
}
测试

image.png