Java中File與byte[]的互轉(zhuǎn)方式
更新時(shí)間:2024年05月30日 15:08:53 作者:看你家貓
這篇文章主要介紹了Java中File與byte[]的互轉(zhuǎn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
Java File與byte[]互轉(zhuǎn)
1、File 轉(zhuǎn)成 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[] 轉(zhuǎn)成 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數(shù)組轉(zhuǎn)換成0和1的二進(jìn)制
可以使用以下代碼將Java中的byte數(shù)組轉(zhuǎn)換為0和1的二進(jìn)制字符串:
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總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實(shí)現(xiàn)簡單超市管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡單超市管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-01-01
springAOP中用joinpoint獲取切入點(diǎn)方法的參數(shù)操作
這篇文章主要介紹了springAOP中用joinpoint獲取切入點(diǎn)方法的參數(shù)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Spring Boot將項(xiàng)目打包成war包的操作方法
這篇文章主要介紹了Spring Boot將項(xiàng)目打包成war包的操作方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09
SpringBoot使用Maven打包異常-引入外部jar的問題及解決方案
這篇文章主要介紹了SpringBoot使用Maven打包異常-引入外部jar,需要的朋友可以參考下2020-06-06
Java中的字符串替換3中實(shí)現(xiàn)總結(jié)
本文詳細(xì)介紹了Java中字符串替換方法,包括replace()、replaceFirst()和replaceAll()的的使用方法和語法格式;并通過實(shí)例展示了如何使用這些方法進(jìn)行字符串替2026-04-04
Java項(xiàng)目的目錄結(jié)構(gòu)詳解
本文主要介紹了Java項(xiàng)目的目錄結(jié)構(gòu)詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02

