public class FileUtile {
/**
* 将文件转换成Byte数组
*/
public static byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将Byte数组转换成文件
*/
public static File getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
// 判断文件目录是否存在
if (!dir.exists()) {
dir.mkdirs();
}
file = new File(filePath + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
return file;
} catch (Exception e) {
e.printStackTrace();
return file;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
© 版权声明
非商业转载或引用请标注本文链接,商业转载或引用请联系站长
部分文章内容可能来自互联网,如有侵权,请通过邮件联系
部分文章内容可能来自互联网,如有侵权,请通过邮件联系
THE END
暂无评论内容