Android详细介绍读写文件的代码
时间: 2023-11-15 08:06:07 浏览: 33
好的,以下是Android读写文件的代码示例:
1. 写入文件:
```
String fileName = "myfile.txt";
String content = "Hello world!";
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
```
2. 读取文件:
```
String fileName = "myfile.txt";
try {
FileInputStream fis = openFileInput(fileName);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
String content = new String(buffer);
Log.i("File Content", content);
} catch (Exception e) {
e.printStackTrace();
}
```
希望能够帮到您!
相关问题
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();
}
请注意,这只是一个简单的示例代码,实际应用中可能需要更多的错误处理和安全性检查。
Android开放读写文件的代码
您可以使用以下代码在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();
```
希望能帮到您!