在 Android 应用程序中,可以通过使用文件读写 API 来保存文件和打开文件。
以下是保存文件和打开文件的简单示例:
保存文件:
```java
String filename = "example.txt";
String content = "Hello, world!";
try {
File file = new File(context.getFilesDir(), filename);
FileWriter writer = new FileWriter(file);
writer.write(content);
writer.close();
Toast.makeText(context, "File saved successfully", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
```
打开文件:
```java
String filename = "example.txt";
try {
File file = new File(context.getFilesDir(), filename);
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
text.append(line);
text.append('\n');
}
reader.close();
Toast.makeText(context, "File content: " + text.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
```
在这个示例中,保存文件时会将字符串 "Hello, world!" 写入到名为 "example.txt" 的文件中,并且通过读取文件获取文件内容并显示在 Toast 中。请注意在实际应用程序中,请确保添加适当的权限和错误处理以确保应用程序的功能正确运行。