java将图片的url转换成File,File转换成二进制流byte
目录
java将图片的url转换成File,File转换成二进制流byte
package com.xqy;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
//java 将图片的 url 转换成 File,File 转换成二进制流 byte
public class PictureUtils {
//将 Url 转换为 File
public static File UrltoFile(String url) throws Exception {
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
httpUrl.connect();
InputStream ins=httpUrl.getInputStream();
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "xie");//System.getProperty("java.io.tmpdir")缓存
if (file.exists()) {
file.delete();//如果缓存中存在该文件就删除
}
OutputStream os = new FileOutputStream(file);
int bytesRead;
int len = 8192;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file;
}
//将File对象转换为byte[]的形式
public static byte[] FileTobyte(File file){
FileInputStream fileInputStream = null;
byte[] imgData = null;
try {
imgData = new byte[(int) file.length()];
//read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(imgData);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imgData;
}
}