package kd.imc.rim.utils; import kd.bos.url.UrlService; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Base64; import static kd.bos.algox.flink.enhance.krpc.impl.DispatcherImpl.log; public class FileOutputStreamExample { public static void main(String[] args) { String filePath = "C:/Users/TR/Desktop/测试1.pdf"; String imgStrToBase64 = getImgStrToBase64(filePath); } /** * 将网络链接图片或者本地图片文件转换成Base64编码字符串 * * @param imgStr 网络图片Url/本地图片目录路径 * @return */ public static String getImgStrToBase64(String imgStr) { InputStream inputStream = null; ByteArrayOutputStream outputStream = null; byte[] buffer = null; try { //判断网络链接图片文件/本地目录图片文件 if (imgStr.startsWith("http://") || imgStr.startsWith("https://")) { // 创建URL URL url = new URL(imgStr); // 创建链接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); inputStream = conn.getInputStream(); outputStream = new ByteArrayOutputStream(); // 将内容读取内存中 buffer = new byte[1024]; int len = -1; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } buffer = outputStream.toByteArray(); } else { inputStream = new FileInputStream(imgStr); int count = 0; while (count == 0) { count = inputStream.available(); } buffer = new byte[count]; inputStream.read(buffer); } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { // 关闭inputStream流 inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { // 关闭outputStream流 outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } // 对字节数组Base64编码 return Base64.getEncoder().encodeToString(buffer); } public static File getNetUrlHttp(String netUrl) { // UrlService.getAttachmentFullUrl(netUrl); //对本地文件命名 File file = null; URL urlfile; InputStream inStream = null; OutputStream os = null; try { file = File.createTempFile("net_url", netUrl); //下载 urlfile = new URL(netUrl); inStream = urlfile.openStream(); os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } } catch (Exception e) { log.error("远程图片获取错误:"+netUrl); e.printStackTrace(); } finally { try { if (null != os) { os.close(); } if (null != inStream) { inStream.close(); } } catch (Exception e) { e.printStackTrace(); } } return file; } }