Android开放读写文件的代码
时间: 2024-02-10 09:45:11 浏览: 21
您可以使用以下代码在Android中进行文件读写:
1.读取文件:
```
File file = new File("文件路径");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
fis.close();
String fileContent = sb.toString();
```
2.写入文件:
```
File file = new File("文件路径");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("写入内容");
bw.flush();
bw.close();
osw.close();
fos.close();
```
希望能帮到您!
相关问题
Android开放如何读写文件
Android开放可以通过使用Java IO或Java NIO库来读写文件。可以使用FileInputStream和FileOutputStream类来读写二进制文件,使用BufferedReader和BufferedWriter类来读写文本文件。另外,也可以使用Android提供的ContentProvider和ContentResolver类来读写系统中的文件。
Android读写文件的详细代码
以下是一个简单的Android读写文件的代码示例:
// 写入文件
String filename = "myfile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件
try (FileInputStream fis = context.openFileInput(filename)) {
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
String fileContents = new String(buffer);
Log.d(TAG, "File contents: " + fileContents);
} catch (IOException e) {
e.printStackTrace();
}
请注意,这只是一个简单的示例代码,实际应用中可能需要更多的错误处理和安全性检查。