搜索词>>io 耗时0.0030
  • Java如何复制目录_Java基础教程系列

    Java如何复制目录,Java基础教程系列,如果要将目录及其包含的所有子文件夹和文件从一个位置复制到另一个位置,请使用下面的代码,该代码使用递归遍历目录结构,然后使用Files.copy()函数复制文件Java如何复制目录,Java基础教程系列,如果要将目录及其包含的所有子文件夹和文件从一个位置复制到另一个位置,请使用下面的代码,该代码使用递归遍历目录结构,然后使用Files.copy()函数复制文件。文件夹复制实例 在此示例中,我将c:\temp下的所有子目录和文件复制到新位置c:\tempNew。import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class DirectoryCopyExample { public static void main(String[] args) throws IOException { //源目录 File sourceFolder = new File("c:\\temp"); //目标目录 File destinationFolder = new File("c:\\tempNew"); //调用复制 copyFolder(sourceFolder, destinationFolder); } /** * 此功能以递归方式将所有子文件夹和文件从sourceFolder复制到destinationFolder * */ private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException { //Check if sourceFolder is a directory or file //If sourceFolder is file; then copy the file directly to new location if (sourceFolder.isDirectory()) { //Verify if destinationFolder is already present; If not then create it if (!destinationFolder.exists()) { destinationFolder.mkdir(); System.out.println("Directory created :: " + destinationFolder); } //Get all files from source directory String files[] = sourceFolder.list(); //Iterate over all files and copy them to destinationFolder one by one for (String file : files) { File srcFile = new File(sourceFolder, file); File destFile = new File(destinationFolder, file); //递归调用复制子目录 copyFolder(srcFile, destFile); } } else { //使用文件复制工具进行复制 Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING); System.out.println("File copied :: " + destinationFolder); } } } 上方代码运行结果:Directory created :: c:\tempNew File copied :: c:\tempNew\testcopied.txt File copied :: c:\tempNew\testoriginal.txt File copied :: c:\tempNew\testOut.txt提示:使用Files.copy()方法,可以复制目录。 但是,目录内的文件不会被复制,因此即使原始目录包含文件,新目录也为空。同样,如果目标文件存在,则复制将失败,除非指定了REPLACE_EXISTING选项。
  • Spring Boot接口统一返回格式 Result对象

    为了方便管理,项目中使用统一风格的返回格式$title(Result.java) import java.io.Serializable; import java.math.BigDecimal; import java.util.UUI为了方便管理,项目中使用统一风格的返回格式$title(Result.java) import java.io.Serializable; import java.math.BigDecimal; import java.util.UUID; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.leftso.system.Log; /** * * <pre> * [Summary] * 通用json数据接口返回口径 * [Detail] * TODO * [Author] * XQLEE * [Version] * v1.0 * 2017年3月27日下午6:32:12 * </pre> */ public final class Result<T> implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Result() { } private Result(Status status, T data, String message) { this.id = UUID.randomUUID().toString().replaceAll("-", ""); this.status = status; this.data = data; this.message = message; } public static <T>Result<T> success(T data) { return new Result(Status.Success, data, ""); } public static <T>Result<T> fail(String message) { return new Result(Status.Fail, "", message); } public static <T>Result<T> unLogin() { return new Result(Status.unLogin, "", "用户未登录"); } private String id; /** 数据内容 **/ private T data; /** 调用接口状态 **/ private Status status; /** 消息,如错误消息 ***/ private String message; /** 接口调用花费时间(单位:秒) **/ private BigDecimal cost; /*** 接口响应时间 ***/ private String time; /** * @return the id */ public String getId() { return id; } /** * @param id * the id to set */ public void setId(String id) { this.id = id; } public static long getSerialVersionUID() { return serialVersionUID; } public T getData() { return data; } public void setData(T data) { this.data = data; } /** * @return the status */ public Status getStatus() { return status; } /** * @param status * the status to set */ public void setStatus(Status status) { this.status = status; } /** * @return the message */ public String getMessage() { return message; } /** * @param message * the message to set */ public void setMessage(String message) { this.message = message; } /** * @return the cost */ public BigDecimal getCost() { return cost; } /** * @param cost * the cost to set */ public void setCost(BigDecimal cost) { this.cost = cost; } /** * @return the time */ public String getTime() { return time; } /** * @param time * the time to set */ public void setTime(String time) { this.time = time; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { try { return JSON.toJSONString(this); } catch (Exception e) { Log.error(e.getMessage(), e, this.getClass()); return JSON.toJSONString(Result.fail("数据处理异常")); } } enum Status { Success, Fail,unLogin } }
  • java实现生成彩色背景图片验证码

    java实现生成彩色背景图片验证码,在登陆和注册可以使用,工具类将图片的IO流通过response输出到浏览器,在浏览器中可以使用 img标签的src属性路径写上该工具类的访问路径即可。1.页面展现 <pre> <code class="language-html"><img id="cerificationCode" src="/front/user/cardCoupon/getCerificationCode" style="margin -left: 62px" onclick="javascript:this.src='/front/user/cardCoupon/getCerificationCode?'+Math.random()"> <a style="color: #dbb04f; font-size: 0.8em; position: relative; bottom: 8px; margin-left: 5px;" onclick="javascript:$('#cerificationCode').click();">换一个</a></code></pre> <!--StartFragment -->注意:onclick="javascript:this.src='/front/user/cardCoupon/getCerificationCode?'+Math.random()"是为了刷新验证码一般都会给个随机数,必须保证每次请求的url不同 ,浏览器才会去服务端获取最新数据,相同的url浏览器优先找自己本地缓存的.<br /> <br /> 2.控制层 <pre> <code class="language-java"> @Controller @RequestMapping("/front/user/cardCoupon") public class CardCouponController extends BaseController { @RequestMapping("/getCerificationCode") public void getCerificationCode(HttpServletRequest request, HttpServletResponse response) { try { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); // 生成随机字串 String verifyCode = VerifyCodeUtils.generateVerifyCode(4); // 存入会话session HttpSession session = request.getSession(true); // 删除以前的 session.removeAttribute("cerificationCode"); session.setAttribute("cerificationCode", verifyCode.toLowerCase()); // 生成图片 int w = 100, h = 30; VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); } catch (IOException e) { log.error("获取验证码失败", e); e.printStackTrace(); } }</code></pre> 3.生成图片验证码工具类 <pre> <code class="language-java">package com.xinfeng.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Random; import javax.imageio.ImageIO; public class VerifyCodeUtils { public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; private static Random random = new Random(); /** * 使用系统默认字符源生成验证码 * * @param verifySize * 验证码长度 * @return */ public static String generateVerifyCode(int verifySize) { return generateVerifyCode(verifySize, VERIFY_CODES); } /** * 使用指定源生成验证码 * * @param verifySize * 验证码长度 * @param sources * 验证码字符源 * @return */ public static String generateVerifyCode(int verifySize, String sources) { if (sources == null || sources.length() == 0) { sources = VERIFY_CODES; } int codesLen = sources.length(); Random rand = new Random(System.currentTimeMillis()); StringBuilder verifyCode = new StringBuilder(verifySize); for (int i = 0; i < verifySize; i++) { verifyCode.append(sources.charAt(rand.nextInt(codesLen))); } return verifyCode.toString(); } /** * 生成随机验证码文件,并返回验证码值 * * @param w * @param h * @param outputFile * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException { String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, outputFile, verifyCode); return verifyCode; } /** * 输出随机验证码图片流,并返回验证码值 * * @param w * @param h * @param os * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException { String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, os, verifyCode); return verifyCode; } /** * 生成指定验证码图像文件 * * @param w * @param h * @param outputFile * @param code * @throws IOException */ public static void outputImage(int w, int h, File outputFile, String code) throws IOException { if (outputFile == null) { return; } File dir = outputFile.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } try { outputFile.createNewFile(); FileOutputStream fos = new FileOutputStream(outputFile); outputImage(w, h, fos, code); fos.close(); } catch (IOException e) { throw e; } } /** * 输出指定验证码图片流 * * @param w * @param h * @param os * @param code * @throws IOException */ public static void outputImage(int w, int h, OutputStream os, String code) throws IOException { int verifySize = code.length(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Random rand = new Random(); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Color[] colors = new Color[5]; Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW }; float[] fractions = new float[colors.length]; for (int i = 0; i < colors.length; i++) { colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; fractions[i] = rand.nextFloat(); } Arrays.sort(fractions); // Color c = getRandColor(200, 250); Color c = new Color(241, 238, 231); g2.setColor(c);// 设置背景色 g2.fillRect(0, 0, w, h); // 绘制干扰线 Random random = new Random(); g2.setColor(getRandColor(160, 200));// 设置线条的颜色 for (int i = 0; i < 20; i++) { int x = random.nextInt(w - 1); int y = random.nextInt(h - 1); int xl = random.nextInt(6) + 1; int yl = random.nextInt(12) + 1; g2.drawLine(x, y, x + xl + 40, y + yl + 20); } // 添加噪点 float yawpRate = 0.05f;// 噪声率 int area = (int) (yawpRate * w * h); for (int i = 0; i < area; i++) { int x = random.nextInt(w); int y = random.nextInt(h); int rgb = getRandomIntColor(); image.setRGB(x, y, rgb); } shear(g2, w, h, c);// 使图片扭曲 // g2.setColor(getRandColor(100, 160)); g2.setColor(new Color(208, 153, 153)); int fontSize = h - 4; Font font = new Font("Algerian", Font.ITALIC, fontSize); g2.setFont(font); char[] chars = code.toCharArray(); for (int i = 0; i < verifySize; i++) { AffineTransform affine = new AffineTransform(); affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2); g2.setTransform(affine); g2.translate(5, 5); g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10); } g2.dispose(); ImageIO.write(image, "jpg", os); } private static Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } private static int getRandomIntColor() { int[] rgb = getRandomRgb(); int color = 0; for (int c : rgb) { color = color << 8; color = color | c; } return color; } private static int[] getRandomRgb() { int[] rgb = new int[3]; for (int i = 0; i < 3; i++) { rgb[i] = random.nextInt(255); } return rgb; } private static void shear(Graphics g, int w1, int h1, Color color) { /* * shearX(g, w1, h1, color); shearY(g, w1, h1, color); */ } private static void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private static void shearY(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } } </code></pre> 4.展现结果<br /> <img src="file:///C:\Users\Administrator\AppData\Roaming\Tencent\Users\1023803178\QQ\WinTemp\RichOle\18955_V`_5P9O)YU]~}{U3R.png" /><img alt="" class="img-thumbnail" src="/assist/images/blog/7826a5549c5e47728c7e9dace3667280.png" /><br />  
  • Java编程中base64图片与文件图片的相互转化工具

    Java编程中处理图片文件与base64串的图片相互转化工具类,方便在编程中处理前端传递过来的base64图片。1.依赖包,maven引入 <pre> <code class="language-xml"> <!--Base64Encoder等工具类 --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <!--/Base64Encoder等工具类 --></code></pre> 2.Java编程代码: <pre> <code class="language-java">package com.leftso.common; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import org.apache.commons.codec.binary.Base64; /** * 图片与base64编码的互转工具 * * @author leftso * */ public class ImageBase64Util { public static void main(String[] args) { try { File image = new File("C:\\Users\\fghfghdf\\Desktop\\temp\\2.png"); String imageStr = image2Base64(new FileInputStream(image)); System.out.println(imageStr); File out = new File("C:\\Users\\fghfghdf\\Desktop\\temp\\3.png"); base642Image(imageStr, new FileOutputStream(out)); } catch (Exception e) { e.printStackTrace(); } } /** * 图片文件转换为base64编码的串 * * @param imageFileInputStream * 图片文件输入流 * @return 编码后的base64串 * @throws IOException * 可能出现IO异常 */ public static String image2Base64(InputStream imageFileInputStream) throws IOException { byte[] data = new byte[imageFileInputStream.available()]; imageFileInputStream.read(data); imageFileInputStream.close(); Base64 base64 = new Base64(); return base64.encodeAsString(data); } /** * base64串转换为图片文件 * * @param base64Image * 图片base64串 * @param outputStream * 输出流 * @throws IOException * 可能出现IO异常 */ public static void base642Image(String base64Image, OutputStream outputStream) throws IOException { Base64 base64 = new Base64(); // 解码 byte[] imageArr = base64.decode(base64Image); InputStream sbs = new ByteArrayInputStream(imageArr); BufferedImage bufferImg = ImageIO.read(sbs); ImageIO.write(bufferImg, "PNG", outputStream); } } </code></pre> <br /> <strong><span style="color:#FF0000">注意<br /> 前端传递过来的图片,一般会有一个前缀,如下<br /> "data:image/jpeg;base64," <br /> 解码之前去掉,否则错误。</span></strong><br />  
  • java语言MD5加密字符串,计算文件的MD5值

    java语言MD5加密字符串,计算文件的MD5值 <pre> <code class="language-java">package org.xqlee.utils.security; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * * <pre> * _________________________INFO_____________________________ * Description : [MD5加密工具类] * Encoding : [UTF-8] * Package : [org.xqlee.utils.md5] * Project : [utils] * Author : [] * CreateDate : [] * Updater : [] * UpdateDate : [] * UpdateRemark: [] * Company : [Shallink Electronic Information] * Version : [v 1.0] * __________________________________________________________ * </pre> */ public class MD5Util { /** * 加密一个输入字符串 * * @param visibleString * 输入一个可见的明码<br> * 类型:java.lang.String * @return 一个加密后的MD5值<br> * 通常用于密码加密 * @throws NoSuchAlgorithmException */ public static String getEnMD5String(String visibleString) throws NoSuchAlgorithmException { MessageDigest md5; // 生成一个MD5加密计算摘要 md5 = MessageDigest.getInstance("MD5"); // 计算md5函数 md5.update(visibleString.getBytes()); // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的 值 String pwdStr = new BigInteger(1, md5.digest()).toString(16); return pwdStr; } /** * 计算文件MD5值 * * @param file * 输入一个文件参数<br> * 类型:java.io.File * @return 该文件的MD5值<br> * 类型:java.lang.String * @throws IOException * IO异常 * @throws NoSuchAlgorithmException * MD5获取实例异常 */ public static String getMd5ForFile(File file) throws IOException, NoSuchAlgorithmException { FileInputStream in = null; in = new FileInputStream(file); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] cache = new byte[2048]; int len; while ((len = in.read(cache)) != -1) { md5.update(cache, 0, len); } in.close(); BigInteger bigInt = new BigInteger(1, md5.digest()); return bigInt.toString(16); } } </code></pre>
  • java图片添加水印logo/大小缩放工具类

    功能说明:1.指定图片大小缩放图片(reSize);2.指定图片的宽度,高度根据比例缩放(reSizeByWith);3.指定图片的高度,宽度根据比例缩放(reSizeByHeight);4.判断是否为图片文件(isImageFile);<strong>Java中图片常用处理工具类 </strong><br /> <br /> 功能说明:<br /> 1.指定图片大小缩放图片(reSize);<br /> 2.指定图片的宽度,高度根据比例缩放(reSizeByWith);<br /> 3.指定图片的高度,宽度根据比例缩放(reSizeByHeight);<br /> 4.判断是否为图片文件(isImageFile);<br /> 5.判断图片格式是否支持(isSupportFormat);<br /> 6.给图片添加水印(markLogo);<br /> <br /> 支持的图片格式: JPG,BMP,GIF,WBMP,PNG,JPEG <pre> <code class="language-java">package net.xqlee.project.demo.fastdfs.clients; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import javax.imageio.ImageIO; import org.springframework.util.StringUtils; /** * <pre> * Java中图片常用处理工具类 * 功能说明: * 1.指定图片大小缩放图片(reSize); * 2.指定图片的宽度,高度根据比例缩放(reSizeByWith); * 3.指定图片的高度,宽度根据比例缩放(reSizeByHeight); * 4.判断是否为图片文件(isImageFile); * 5.判断图片格式是否支持(isSupportFormat); * 6.给图片添加水印(markLogo); * 支持的图片格式: * JPG,BMP,GIF,WBMP,PNG,JPEG * </pre> * * @author xq * */ public class ImageUtils { /**** * 判断是否为图片文件,如果是图片文件则返回BufferedImage对象,反之则返回null * * @param imageFile * 图片文件 * @return BufferedImage * @throws IOException * IO异常 */ public static BufferedImage isImageFile(File imageFile) throws IOException { BufferedImage image = isImageFile(new FileInputStream(imageFile)); return image; } /**** * 判断是否为图片文件,如果是图片文件则返回BufferedImage对象,反之则返回null * * @param imageFileInputStream * 图片文件的输入流 * @return BufferedImage * @throws IOException * IO异常 */ public static BufferedImage isImageFile(InputStream imageFileInputStream) throws IOException { BufferedImage image = ImageIO.read(imageFileInputStream); return image; } /** * 图片格式是否支持 * * @param formatName * 图片格式名称 * @return 是否支持 */ public static boolean isSupportFormat(String formatName) { if (StringUtils.isEmpty(formatName)) { return false; } String supportTypes = Arrays.toString(ImageIO.getReaderFormatNames()); if (supportTypes.indexOf(formatName) == -1) { return false; } else { return true; } } /** * 重置图片到指定的宽和高 * * @param imageFile * @param imageFileOutputStream * @param formatName * @param newWith * @param newHeight * @throws IOException */ public static void reSize(InputStream imageFile, OutputStream imageFileOutputStream, String formatName, int newWith, int newHeight) throws IOException { // 1.判断文件格式是否支持 if (!isSupportFormat(formatName)) { throw new IOException( "Format Not Support:" + formatName + ",Support" + Arrays.toString(ImageIO.getReaderFormatNames())); } // 1.判断是否为图片文件 BufferedImage bufferedImage = isImageFile(imageFile); if (bufferedImage == null) { throw new IOException("Input File Is Not Image File."); } // 2.调整到指定宽高 BufferedImage newImage = new BufferedImage(newWith, newHeight, bufferedImage.getType()); // 3.执行重构画操作 Graphics2D graphics = newImage.createGraphics(); graphics.drawImage(bufferedImage, 0, 0, newWith, newHeight, Color.LIGHT_GRAY, null); graphics.dispose(); // 4.输出缩略图片 ImageIO.write(newImage, formatName, imageFileOutputStream); } /** * 指定图片的宽,高根据比例压缩 * * @param imageFile * 远图片 * @param imageFileOutputStream * 新图片输出 * @param formatName * 图片格式 * @param newWith * 新的宽度 * @throws IOException */ public static void reSizeByWith(InputStream imageFile, OutputStream imageFileOutputStream, String formatName, int newWith) throws IOException { // 1.判断文件格式是否支持 if (!isSupportFormat(formatName)) { throw new IOException( "Format Not Support:" + formatName + ",Support" + Arrays.toString(ImageIO.getReaderFormatNames())); } // 1.判断是否为图片文件 BufferedImage bufferedImage = isImageFile(imageFile); if (bufferedImage == null) { throw new IOException("Input File Is Not Image File."); } // 2.调整到指定宽 int oldWith = bufferedImage.getWidth(); int oldHeigth = bufferedImage.getHeight(); // 计算比例 BigDecimal newWithBig = new BigDecimal(newWith); float ratio = newWithBig.divide(new BigDecimal(oldWith), 2, RoundingMode.HALF_UP).floatValue(); int newHeight = (int) (oldHeigth * ratio); if (newHeight == 0) {// 太小的时候默认原始高度 newHeight = oldHeigth; } BufferedImage newImage = new BufferedImage(newWith, newHeight, bufferedImage.getType()); // 3.执行重构画操作 Graphics2D graphics = newImage.createGraphics(); graphics.drawImage(bufferedImage, 0, 0, newWith, newHeight, null); graphics.dispose(); // 4.输出缩略图片 ImageIO.write(newImage, formatName, imageFileOutputStream); } public static void reSizeByHeight(InputStream imageFile, OutputStream imageFileOutputStream, String formatName, int newHeight) throws IOException { // 1.判断文件格式是否支持 if (!isSupportFormat(formatName)) { throw new IOException( "Format Not Support:" + formatName + ",Support" + Arrays.toString(ImageIO.getReaderFormatNames())); } // 1.判断是否为图片文件 BufferedImage bufferedImage = isImageFile(imageFile); if (bufferedImage == null) { throw new IOException("Input File Is Not Image File."); } // 2.调整到指定宽 int oldWith = bufferedImage.getWidth(); int oldHeigth = bufferedImage.getHeight(); // 计算比例 BigDecimal newHeightBig = new BigDecimal(newHeight); float ratio = newHeightBig.divide(new BigDecimal(oldHeigth), 2, RoundingMode.HALF_UP).floatValue(); int newWith = (int) (oldWith * ratio); if (newWith == 0) {// 太小的时候默认原始高度 newWith = oldWith; } BufferedImage newImage = new BufferedImage(newWith, newHeight, bufferedImage.getType()); // 3.执行重构画操作 Graphics2D graphics = newImage.createGraphics(); graphics.drawImage(bufferedImage, 0, 0, newWith, newHeight, null); graphics.dispose(); // 4.输出缩略图片 ImageIO.write(newImage, formatName, imageFileOutputStream); } /** * 添加水印LOGO * * @param targetImage * 需要添加水印的原图 * @param logoImage * 水印图片/水印Logo * @param x * Logo存放的x轴(原图的左上角为0,0) * @param y * Logo存放的y轴(原图的左上角为0,0) * @throws IOException * IO异常 */ public static void markLogo(BufferedImage targetImage, BufferedImage logoImage, int x, int y) { Graphics2D g = targetImage.createGraphics(); g.drawImage(targetImage, 0, 0, targetImage.getWidth(), targetImage.getHeight(), null); g.drawImage(logoImage, x, y, logoImage.getWidth(), logoImage.getHeight(), null); g.dispose(); } /** * 添加水印LOGO,执行后新的图片将存放于targetImage里面 * * @param targetImage * 需要添加水印的图片文件流 * @param targetImageFormat * 图片格式 * @param logoImage * 水印图片流/logo图片流 * @param x * Logo存放的x轴(原图的左上角为0,0) * @param y * Logo存放的y轴(原图的左上角为0,0) * @param imageFileOutputStream * 最终图片文件输出流 * @throws IOException * IO异常需要捕获 */ public static void markLogo(InputStream targetImage, String targetImageFormat, InputStream logoImage, int x, int y, OutputStream imageFileOutputStream) throws IOException { if (!isSupportFormat(targetImageFormat)) { throw new IOException("Image Format Not Support." + targetImageFormat + ",Support" + Arrays.toString(ImageIO.getReaderFormatNames())); } BufferedImage targetImageBuffere = ImageIO.read(targetImage); BufferedImage logoImageBuffere = ImageIO.read(logoImage); markLogo(targetImageBuffere, logoImageBuffere, x, y); ImageIO.write(targetImageBuffere, targetImageFormat, imageFileOutputStream); } /** * 添加水印LOGO * * @param targetImage * 需要添加logo的图片 * @param logoImage * logo图片 * @param x * Logo存放的x轴(原图的左上角为0,0) * @param y * Logo存放的y轴(原图的左上角为0,0) * @param imageFileOutputStream * 最终图片文件输出流 * @throws IOException * IO异常需要捕获 */ public static void markLogo(File targetImage, File logoImage, int x, int y, OutputStream imageFileOutputStream) throws IOException { String filename = targetImage.getName(); String format = filename.substring(filename.indexOf(".") + 1).toUpperCase(); markLogo(new FileInputStream(targetImage), format, new FileInputStream(logoImage), x, y, imageFileOutputStream); } public static void main(String[] args) { try { //@formatter:off // 重置大小测试 //指定宽高 // reSize( // new FileInputStream(new File("C:\\Users\\xq\\Pictures\\1.jpg")), // new FileOutputStream(new File("C:\\Users\\xq\\Pictures\\1-t.jpg")), "jpg", 400, 400); //指定宽 // reSizeByWith( // new FileInputStream(new File("C:\\Users\\xq\\Pictures\\1.jpg")), // new FileOutputStream(new File("C:\\Users\\xq\\Pictures\\1-t.jpg")), // "jpg", 400); //指定高度 // reSizeByHeight( // new FileInputStream(new File("C:\\Users\\xq\\Pictures\\0.png")), // new FileOutputStream(new File("C:\\Users\\xq\\Pictures\\1-t-h.png")), // "png", 400); // logo水印测试 // markLogo( // new FileInputStream(new File("C:\\Users\\xq\\Pictures\\0.jpg")), "JPG", // new FileInputStream( new File("C:\\Users\\xq\\Pictures\\tx.jpg")), 0,0, // new FileOutputStream(new File("C:\\Users\\xq\\Pictures\\1-tx.jpg"))); markLogo( new File("C:\\Users\\xq\\Pictures\\0.png"), new File("C:\\Users\\xq\\Pictures\\tx.jpg"), 0, 0, new FileOutputStream(new File("C:\\Users\\xq\\Pictures\\1-tx.png"))); System.out.println(Arrays.toString(ImageIO.getReaderFormatNames())); //@formatter:off } catch (Exception e) { e.printStackTrace(); } } } </code></pre>
  • java 以http client的post/get方式访问指定url

    java 以http client的post/get方式访问指定url <pre> <code class="language-java"> import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import com.xqlee.dev.project.core.utils.io.IOUtil; /** * * * <pre> * _________________________INFO_____________________________ * | Description : [HTTP客服端] * | Encoding : [UTF-8] * | Package : [org.xqlee.utils.net] * | Project : [utils] * | Author : [] * | CreateDate : [] * | Updater : [] * | UpdateDate : [] * | UpdateRemark: [] * | Company : [Shallink Electronic Information] * | Version : [v 1.0] * | Libs : [] * __________________________________________________________ * </pre> */ public class HttpClient { public static String doGet(String url, String param) throws IOException { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 防止乱码 String line; while ((line = in.readLine()) != null) { result += line; result+=IOUtil.LINE_SEPARATOR; } } catch (IOException e) { throw e; } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { throw e2; } } return result; } public static String doPost(String url, String param) throws IOException { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line; while ((line = in.readLine()) != null) { result += line; result+=IOUtil.LINE_SEPARATOR; } } catch (IOException e) { throw e; } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { throw ex; } } return result; } } </code></pre>
  • Java编程POI处理Excel中添加图片

    Java编程中,很多报表系统需要导出Excel文件,并且某些时候需要导出一定的图形统计,其实就是将图片放在Excel中,下面讲解Java如何实现Excel图片编辑插入<pre> <code class="language-java">import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelPicTest { public static void main(String[] args) { try { // 创建一个excel文件 XSSFWorkbook workbook = new XSSFWorkbook(); // 获取第一个表格 Sheet sheet0 = workbook.createSheet(); // 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点) XSSFDrawing patriarch = (XSSFDrawing) sheet0.createDrawingPatriarch(); // 图片定位 // 参数说明 // int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, // int row2 // dx1,dy1,dx2,dy2一般用不到,标识单元格内的x,y // **********************以下四个参数定位图片的具体存放位置********************* // col1:the column (0 based) of the first cell. // row1:the row (0 based) of the first cell. // col2: the column (0 based) of the second cell. // row2: the row (0 based) of the second cell. // **********************以上四个参数用来定位两个单元格,都是从索引0开始的************ // col1/row1定位图片开始的左上角位置(包含当前单元格),这里传递的1,1表示图片左上角为第2行(索引从0开始1表示第二行)第二个单元格(索引从0开始1表示第二行)开始 // col2/row2定位图片的右下角位置(不含),这里的8,5标识结束为6行(索引从0开始1表示第二行)第9格单元格(索引从0开始1表示第二行)结束 XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 8, 5); // FileInputStream fis = new FileInputStream(new File("d:/1.jpg")); byte[] image = input2byte(fis);// 图片 patriarch.createPicture(anchor, workbook.addPicture(image, HSSFWorkbook.PICTURE_TYPE_PNG));// 写图片 // excel文件输出 File excel = new File("d://t1.xlsx"); workbook.write(new FileOutputStream(excel)); workbook.close(); } catch (Exception e) { e.printStackTrace(); } } public static final byte[] input2byte(InputStream inStream) throws IOException { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = inStream.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } byte[] in2b = swapStream.toByteArray(); return in2b; } } </code></pre> <br /> 执行结果:<br /> <img alt="Java编程Excel" class="img-thumbnail" src="/assist/images/blog/56f279cc-ec05-49c8-895a-d1d40f31c06c.png" style="height:410px; width:758px" />
  • eclipse如何关闭java代码中某些部分/片段代码不被格式化

    eclipse如何关闭java代码中某些部分/片段代码不被格式化,eclipse,代码部分不被格式化,How to turn off the Eclipse code formatter for certain sections of Java code?eclipse如何关闭java代码中某些部分/片段代码不被格式化,eclipse,代码部分不被格式化,<br /> How to turn off the Eclipse code formatter for certain sections of Java code?<br /> <br /> 1.设置eclipse开启Off/On tags<br /> <br /> 依次点击菜单<br /> preferences->Java->Code Style->Formatter<br /> 点击Edit<br /> <img alt="1" class="img-thumbnail" src="/assist/images/blog/d2fc6ee509064f309342ae36d146bb42.png" /><br /> <br /> 找到tag,点击enable Off/On tags<br /> <img alt="2" class="img-thumbnail" src="/assist/images/blog/44a828ea10834828a6587602e9e42c03.png" /><br /> <br /> <br /> 在不想被格式化的代码之间添加以下注释标签即可<br />   <pre> <code class="language-java">import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.springframework.util.Base64Utils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; import com.cqax.axschoolweb2.common.pojo.Result; /** * 验证码公用处理类 * * @author xq * */ @RestController public class ValidationCodeController { //@formatter:off /** * * @api {get} /apis/validation/getcode.json 获取验证码 * * @apiName GetValidateCode * * @apiGroup Validation * * @apiParam {String} [timeStamp] 时间戳 * * @apiSuccessExample {String} 返回值: * { "id": "1be34f4a324c4123b0325ecf0593d70e", "data": { "image": "iVBORwCCAAAAAAAAAAAAAAAAA==" }, "code": "00000", "dateTime": "2017-05-23 14:00:23", "msg": null } * */ //@formatter:on @GetMapping("/apis/validation/getcode.json") public Result getCode() { try { InputStream is = new FileInputStream(new File("e:/2.png")); ByteArrayOutputStream bao = new ByteArrayOutputStream(); byte[] cache = new byte[4096]; while (is.read(cache) != -1) { bao.write(cache); } String rs = Base64Utils.encodeToString(bao.toByteArray()); JSONObject obj = new JSONObject(); obj.put("image", rs); is.close(); return Result.success(obj); } catch (Exception e) { return Result.fail("eeeee", "错误,异常," + e.getMessage()); } } //@formatter:off /** * @api {get} /apis/validation/compare.json 对比验证码 * * @apiName CompareValidateCode * * @apiGroup Validation * * @apiParam {String} vcode 验证码 * * @apiSuccessExample {json} 返回值: * { "id":"f47611a1a7ee4d4c8c0420a4f7e4b228", "data":{ "result":true }, "code":"00000", "dateTime":"2017-05-23 14:41:36", "msg":null } */ //@formatter:on @GetMapping("/apis/validation/compare.json") public Result compare(String vcode) { JSONObject obj = new JSONObject(); obj.put("result", true);// 对比结果 return Result.success(obj); } public Result getPhoneCode(){ JSONObject obj=new JSONObject(); return null; } } </code></pre> <br />
  • spring boot FastDFS Java client使用-Java编程

    Java编程之spring boot FastDFS Java client使用,Java编程,FastDFS Java客户端<h2>一、获取FastDFS Java的客户端链接工具</h2> 由于maven库中并没有编译好的jar工具包,目前只能通过GitHub下载源码自己打包成jar<br /> 下载地址:<a href="https://github.com/happyfish100/fastdfs-client-java" rel="external nofollow" target="_blank">点击去下去</a><br /> <br /> 如果通过浏览器直接下载,则下载后是一个zip压缩包。<br /> 1.解压zip包<br /> 2.eclipse通过已存在的maven项目方式导入<br /> 3.执行maven install命令打包<br /> <br /> 打包完成后再target目录下有打包好的jar文件:<br /> <strong>fastdfs-client-java-1.27-SNAPSHOT.jar</strong><br />   <h2>二、导入spring boot项目</h2> 创建一个spring boot项目,在创建好的项目中创建一个lib的文件夹,将上面打包的jar文件复制进去。然后打开spring boot项目的pom.xml文件,添加本地依赖如下: <pre> <code class="language-xml"> <!-- fastfds 客户端 |https://github.com/happyfish100/fastdfs-client-java --> <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.27-SNAPSHOT</version> <scope>system</scope> <systemPath>${project.basedir}/lib/fastdfs-client-java-1.27-SNAPSHOT.jar</systemPath> </dependency></code></pre> <h2>三、配置文件</h2> 在spring boot项目的resource目录下创建一个fdfs_client.conf文件,内容如下: <pre> <code>#注1:tracker_server指向您自己IP地址和端口,1-n个 #注2:除了tracker_server,其它配置项都是可选的 #注3:.conf 配置文件文件所在位置可以是项目classpath(或OS文件系统目录比如/opt/): #注4:.conf 配置文件优先按OS文件系统路径读取,没有找到才查找项目classpath,尤其针对linux环境下的相对路径 #注5:其他相关参考:https://github.com/happyfish100/fastdfs-client-java connect_timeout = 120 network_timeout = 130 charset = UTF-8 http.tracker_http_port = 80 http.anti_steal_token = no http.secret_key = FastDFS1234567890 tracker_server = 192.168.8.202:22122</code></pre> 其中里面的tracker_server 以及端口均需要根据自身使用的实际请来修改 <h2><br /> 四、编写一个公用的Java 的fastdfs客户端</h2> 首先需要创建一个FastDFS的文件辅助类:<br /> <strong>FastDSFile.java</strong> <pre> <code class="language-java">public class FastDSFile { private String name; private byte[] content; private String ext; private String md5; public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public String getExt() { return ext; } public void setExt(String ext) { this.ext = ext; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } } </code></pre> <br /> <strong>FastDFSClient.java</strong> <pre> <code class="language-java">import java.io.File; import java.io.IOException; import org.csource.common.MyException; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient1; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerServer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import com.alibaba.fastjson.JSONArray; /** * fastDFS文件服务Java客户端实现,所有执行方法均为静态方法。 * * @author xq * */ public class FastDFSClient { /** * 客户端 */ private static StorageClient1 storageClient1 = null; // 初始化客户端,加载类时候执行片段 static { try { Resource resource = new ClassPathResource("fdfs_client.conf"); File file = resource.getFile(); String configFile = file.getAbsolutePath(); ClientGlobal.init(configFile); // TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group); // TrackerServer trackerServer = trackerClient.getConnection(); // StorageServer storageServer = trackerClient.getStoreStorage(trackerServer); // storageClient1 = new StorageClient1(trackerServer, storageServer); System.out.println("FastDFS Client Init Success!"); } catch (Exception e) { e.printStackTrace(); System.out.println("FastDFS Client Init Fail!"); } } /*** * 文件上传 * * @param fastDSFile * @return * @throws IOException * @throws MyException */ public static JSONArray upload(FastDSFile fastDSFile) throws IOException, MyException { String[] uploadResult = storageClient1.upload_file(fastDSFile.getContent(), fastDSFile.getExt(), null); // String arr = JSONArray.toJSONString(uploadResult); JSONArray arr = (JSONArray) JSONArray.toJSON(uploadResult); return arr; } /** * 文件下载 * * @param groupName * @param remoteFileName * @return * @throws IOException * @throws MyException */ public static byte[] download(String groupName, String remoteFileName) throws IOException, MyException { return storageClient1.download_file(groupName, remoteFileName); } /** * 文件删除 * * @param groupName * @param remoteFileName * @throws Exception * @return 返回0成功;非0失败. */ public static int delete(String groupName, String remoteFileName) throws Exception { return storageClient1.delete_file(groupName, remoteFileName); } } </code></pre> <h2>五、编写测试</h2> <strong>DemoSpringbootFastdfsApplicationTests.java</strong> <pre> <code class="language-java">import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.alibaba.fastjson.JSONArray; import net.xqlee.project.demo.fastdfs.clients.FastDFSClient; import net.xqlee.project.demo.fastdfs.clients.FastDSFile; @RunWith(SpringRunner.class) @SpringBootTest public class DemoSpringbootFastdfsApplicationTests { @Test public void contextLoads() { try { FileInputStream fis = new FileInputStream(new File("C:/Users/xq/Pictures/tx.jpg")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] cache = new byte[4096]; while (fis.read(cache) != -1) { bos.write(cache); } fis.close(); FastDSFile fastDSFile = new FastDSFile(); fastDSFile.setContent(bos.toByteArray()); fastDSFile.setExt("jpg"); // -------上传---- JSONArray rs = FastDFSClient.upload(fastDSFile); System.out.println("上传结束:" + rs); // -------下载---- byte[] dfile = FastDFSClient.download(rs.getString(0), rs.getString(1)); FileOutputStream fos = new FileOutputStream(new File("C:/Users/xq/Pictures/tx-fdfs.jpg")); fos.write(dfile); fos.flush(); fos.close(); // -------删除----- int ds=FastDFSClient.delete(rs.getString(0), rs.getString(1)); // System.out.println("Delete:"+ds); System.out.println("---End----"); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <br /> 运行测试,可以看到在上传图片的目录下多了一个名为tx-fdfs.jpg的文件