andriod 内部存储与读取案例
时间: 2024-01-11 08:02:40 浏览: 24
下面是一个简单的 Android 内部存储与读取案例:
1. 创建一个新的 Android 项目并打开 MainActivity.java 文件。
2. 在 onCreate() 方法中添加以下代码:
```java
String fileName = "example.txt";
String content = "Hello, World!";
try {
FileOutputStream fOut = openFileOutput(fileName, MODE_PRIVATE);
fOut.write(content.getBytes());
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fin = openFileInput(fileName);
int c;
StringBuilder stringBuilder = new StringBuilder();
while ((c = fin.read()) != -1) {
stringBuilder.append(Character.toString((char) c));
}
fin.close();
String readContent = stringBuilder.toString();
Log.d("MainActivity", "Content: " + readContent);
} catch (Exception e) {
e.printStackTrace();
}
```
3. 运行应用程序并查看输出日志。应该看到以下内容:
```java
D/MainActivity: Content: Hello, World!
```
这个例子使用 openFileOutput() 方法将一个字符串写入名为 example.txt 的文件中。然后使用 openFileInput() 方法读取该文件并将其内容存储在一个字符串中。最后,使用 Log.d() 方法输出读取的内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)