android 一个一个字节读写文件示例代码
时间: 2024-01-26 22:04:38 浏览: 78
以下是一个简单的 Android Java 代码示例,演示如何按字节读写文件:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteFileReadWrite {
public static void main(String[] args) {
String filePath = "path/to/file"; // 文件路径
byte[] data = "Hello World!".getBytes(); // 要写入的数据
// 写入文件
try {
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(data);
fos.close();
System.out.println("数据已写入文件。");
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件
try {
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = fis.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, length));
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码将字符串 "Hello World!" 转换为字节数组,并将其写入指定的文件中。接着,它读取文件中的字节,并将它们转换为字符串并打印到控制台上。你可以根据你的需求修改这段代码,例如更改文件路径、更改要写入的数据等。
阅读全文
相关推荐
















