java 文件和byte数组相互转换

来源:互联网 发布:微软安全防护软件 编辑:程序博客网 时间:2024/06/05 12:50

/**

* 根据文件生byte数组
*/
public static byte[] getBytes(File file) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}


/**
* 根据byte数组,生成文件
*/
public void getFile(byte[] bfile, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File path = new File(filePath);
if (!path.exists())
path.mkdirs();
if (!path.exists()) {
Log.e(TAG, "Failed to create file path. Check your card.");
return;
}


file = new File(filePath, fileName);


fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}

原创粉丝点击