Java中File与byte[]的互转方式
更新时间:2024年05月30日 15:08:53 作者:看你家猫
这篇文章主要介绍了Java中File与byte[]的互转方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Java File与byte[]互转
1、File 转成 byte[]
public static byte[] getImageStream(String imageUrl,
HttpServletRequest request) {
ServletContext application = request.getSession().getServletContext();
String url = application.getRealPath("/")+imageUrl;
byte[] buffer = null;
File file = new File(url);
FileInputStream fis;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
if(file.exists()) {
file.delete();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
2、byte[] 转成 File
public static void readBin2Image(byte[] byteArray, String targetPath) {
InputStream in = new ByteArrayInputStream(byteArray);
File file = new File(targetPath);
String path = targetPath.substring(0, targetPath.lastIndexOf("/"));
if (!file.exists()) {
new File(path).mkdir();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java byte数组转换成0和1的二进制
可以使用以下代码将Java中的byte数组转换为0和1的二进制字符串:
byte[] bytes = ...;
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
}
System.out.println(binary.toStri总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java中使用HttpPost发送form格式的请求实现代码
在Java中使用HttpPost发送form格式的请求,可以使用Apache HttpClient库来实现,这篇文章主要介绍了Java中使用HttpPost发送form格式的请求,本文给大家展示示例代码,需要的朋友可以参考下2023-08-08
SpringBoot使用Redis对用户IP进行接口限流的项目实践
本文主要介绍了SpringBoot使用Redis对用户IP进行接口限流,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-07-07


最新评论