例如网络图片文件转换可以使用的如下:
package utils;
import com.xx.util.file.FileUtils;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.net.*;
/**
* 文件工具
* @author zmd
*/
public class FileUtil {
/**
* 网络文件URL转换成FileInputStream
* @param netUrl
* @return
*/
public static FileInputStream netUrlToFileFileInputStream(String netUrl){
FileInputStream fileInputStream = null;
try {
URL url = new URL(netUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为HEAD,这样服务器只返回状态码,不会传输内容
connection.connect();
InputStream inputStream = connection.getInputStream();
fileInputStream = convertToFileInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return fileInputStream;
}
/**
* inputStream 转换成 FileInputStream
* @param inputStream
* @return
* @throws IOException
*/
public static FileInputStream convertToFileInputStream(InputStream inputStream) throws IOException {
File tempFile = File.createTempFile("temp", ".jpeg");
tempFile.deleteOnExit();
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
return new FileInputStream(tempFile);
}
/**
* 获取网络文件大小 kb
* @param netUrl
* @return
*/
public static Long getImageSize(String netUrl){
HttpURLConnection connection = null;
try {
URL url = new URL(netUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为HEAD,这样服务器只返回状态码,不会传输内容
connection.setRequestMethod("HEAD");
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
// 获取图片字节长度,即大小
assert connection != null;
return connection.getContentLengthLong();
}
/**
* 网络文件转换成File
* @param netUrl
* @return
*/
public static File getFileByNetUrl(String netUrl){
File tempFile = null;
try {
tempFile = File.createTempFile("temp", ".jpeg");
} catch (IOException e) {
e.printStackTrace();
}
if (tempFile != null){
tempFile.deleteOnExit();
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
FileInputStream inputStream = netUrlToFileFileInputStream(netUrl);
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(tempFile.getAbsolutePath());
}
return tempFile;
}
}