Java Android 二进制文件读写

https://blog.csdn.net/u012734708/article/details/88354539

1.读取android工程中本地二进制文件
Android studio工程目录中有二进制文件abcd.raw 。
二进制文件所放目录 app/src/main/assets/abcd.raw

1.1一次性读取二进制文件
private byte[] readLocalFile() throws IOException {
String fileName = "abcd.raw";
InputStream inputStream = getAssets().open(fileName);
byte[] data = toByteArray(inputStream);
inputStream.close();
return data;
}
private byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}

1.2 分段读取二进制文件,一次读取1024个字节
byte[] buffer = new byte[1024];
private void readLocalFile() throws IOException {
String fileName = "abcd.raw";
InputStream inputStream = getAssets().open(fileName);
int n = -1;
while ((n = inputStream.read(buffer,0,1024)) != -1) {
//buffer为读出来的二进制数据,长度1024,最后一段数据小于1024
}
inputStream.close();
}
2.分段读取手机目录中本地二进制文件
手机目录中有二进制文件abcd.raw 。
二进制文件所在手机目录 /sdcard/abcd.raw

private void readLocalFile() {
FileInputStream inputStream = null;
File file = new File("/sdcard/abcd.raw");
try {
inputStream = new FileInputStream(file);
byte buffer[] = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer,0,buffer.length))>0) {
//buffer为读出来的二进制数据,长度1024,最后一段数据小于1024
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.写入手机目录二进制文件
写入到手机目录中有二进制文件/sdcard/aaa.raw 。

FileOutputStream fos = null;
private void openPCMfile(byte[] bytes) {
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+ "aaa.raw");
if (!f.exists()) {
File parentFile = f.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fos = new FileOutputStream(f);
fos.write(bytes, 0, bytes.length);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

上一篇:properties文档读取工具类


下一篇:通过手写服务器的方式,立体学习Http