一、图片
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
@Slf4j
public class ImageUtils {
public static byte[] getImageBytes(String imgUrl) {
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpUrl = null;
try {
url = new URL(imgUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while ((len = is.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 对字节数组Base64编码
return outStream.toByteArray();
} catch (ConnectException e) {
log.error("获取图片时连接异常,url:{}",imgUrl,e);
} catch (MalformedURLException e) {
log.error("url出现异常,url:{}",imgUrl,e);
} catch (IOException e) {
log.error("读取图片时发生异常,url:{}",imgUrl,e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpUrl != null) {
httpUrl.disconnect();
}
}
return null;
}
//做校验使用
public static void bytesToImage(byte[] bytes1) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File("C:\\Users\\Desktop\\test\\test.jpg");
ImageIO.write(bi1, "jpg", w2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
获取配置文件
我是只读取一个配置文件,需要读取不同的配置文件自己改改就好,难度不大。
statis代码块是默认只加载一次的,可以自行了解。
import lombok.extern.slf4j.Slf4j;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Slf4j
public class PropertiesUtil {
private static Properties props;
static {
loadProps("config");
}
private static void loadProps(String propName) {
props = new Properties();
InputStream in = null;
try {
/*
* <!--第一种,通过类加载器进行获取properties文件流-->
* in = PropertyUtil.class.getClassLoader().getResourceAsStream(
* "jdbc.properties");
* <!--第二种,通过类进行获取properties文件流-->
*/
in = PropertiesUtil.class.getResourceAsStream("/"+propName+".properties");
props.load(in);
} catch (FileNotFoundException e) {
log.error(propName+".properties文件未找到",e);
} catch (IOException e) {
log.error("出现IOException",e);
} finally {
try {
if (null != in) {
in.close();
}
} catch (IOException e) {
log.error(".properties文件流关闭出现异常",e);
}
}
}
public static String getProperties(String key) {
if (null == props) {
return null;
}
return props.getProperty(key);
}
}
用法:
private static String brokerURL;
static {
ActiveMqUtil.brokerURL = PropertiesUtil.getProperties("linewell.activemq.brockerURL");
}