byte字节流存入File文件
- 简述
在项目中存在需要把一些字节流信息存入文件,然后显示出来,比如照片,pdf等文件.byte字节流是传输信息的基本方式.下面是把字节信息转化为临时文件存储,然后返回文件路径,如果想学习文件File 的操作的api可以自己先百度一下.
/**
* 根据byte数组,生成文件
* @param bfile byte字节流
* @param filePath 文件存放目录
* @param fileName 文件名称(不带后缀的)
* @return
*/
public String getFile(byte[] bfile, String filePath,String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
String path = "";
try {
File dir = new File(filePath);
if(!dir.exists()&&!dir.isDirectory()){//判断文件目录是否存在
dir.mkdirs();
}
//创建临时文件的api参数 (文件前缀,文件后缀,存放目录)
file = File.createTempFile(fileName, IMG_SUFFIX, dir);
tempFileName = file.getName();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
path = file.getPath();
return path;
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建临时文件失败!" + e.getMessage());
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
这样就完成了存入临时文件,返回文件路径是方便删除文件,防止占用存储空间.