安卓 将数据存到文件中
时间: 2024-05-12 20:20:36 浏览: 20
在安卓中,将数据存到文件中有多种方式,下面列举其中两种常用的方法:
1. 使用FileOutputStream类和BufferedWriter类
```
String fileName = "data.txt";
String data = "Hello world!";
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(data);
bw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
```
2. 使用SharedPreferences类
```
String fileName = "data";
String data = "Hello world!";
SharedPreferences sharedPreferences = getSharedPreferences(fileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("data", data);
editor.apply();
```
以上两种方法都可以将数据存储到文件中,但是它们的适用场景不同。如果需要频繁地读写数据,建议使用SharedPreferences类,如果需要存储大量数据或者需要对数据进行复杂的操作,建议使用FileOutputStream类和BufferedWriter类。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)