java 文件和byte互转的实例

网友投稿 257 2023-03-16


java 文件和byte互转的实例

实例如下所示:

/**

* 获得指定文件的byte数组

*/

private byte[] getBytes(String filePath){

byte[] buffer http://= null;

try {

File file = new File(filePath);

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 static void getFile(byte[] bfile, String filePath,http://String fileName) {

BufferedOutputStream bos = null;

FileOutputStream fos = null;

File file = null;

try {

File dir = new File(filePath);

if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在

dir.mkdirs();

}

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();

}

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详谈DOM简介及节点、属性、查找节点的方法
下一篇:API接口文档例子(api接口文档怎么看)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~