您的位置:首页 > 编程语言 > Java开发

Java开发常用的方法-每天都会更新

2019-03-18 13:50 134 查看

文章目录

  • 字符串常用方法:
  • Http请求工具:
  • 密码加密:
  • 获取IP方法:
  • 文件上传常用方法:

    1.判断上传文件的类型

    /**
    * 判断上传文件的类型
    *
    * @param file 文件
    * @param excludeImg 是不是该后缀名 (jpg,png,exe)
    * @return true 是规定的类型 false 不是
    */
    public static boolean getImgType(MultipartFile file, String excludeImg) {
    // 判断参数是否为空
    if(file.getSize() == 0 ){
    return false;
    }
    // 把字符串转化为数组
    String[] imgArr = excludeImg.split(",");
    for (int i = 0; i < imgArr.length; i++) {
    // 获取文件名字
    String fileName = file.getOriginalFilename();
    // 获取文件后缀
    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
    if(imgArr[i].equals(suffix)){
    return true;
    }
    }
    return false;
    }

    2.判断上传文件的类型

    /**
    * 获取项目运行所在的目录并创建指定文件夹
    *
    * @param subdirectory 文件夹名称
    * @return
    */
    public static String getPath(String subdirectory) {
    //获取跟目录---与jar包同级目录的upload目录
    File upload = null;
    try {
    // 获取项目中所在的路径
    // C:\Users\Administrator\Desktop\SpringBoot\xx\xx-common\target\classes
    File path = new File(ResourceUtils.getURL("classpath:").getPath());
    // 判断目录是否存在
    if (!path.exists()) path = new File("");
    // 项目运行目录 + subdirectory
    upload = new File(path.getAbsolutePath(), subdirectory);
    //如果不存在则创建目录
    if (!upload.exists()) upload.mkdirs();
    String realPath = upload + "/";
    return realPath;// C:\Users\Administrator\Desktop\SpringBoot\XX\XX-common\target\classes\123/
    } catch (FileNotFoundException e) {
    LOG.info("GetServerPathUtil===>获取服务器路径发生错误!");
    throw new RuntimeException("获取服务器路径发生错误!");
    }
    }

    3.文件上传工具

    /**
    * 文件上传工具
    * @param file 文件
    * @param subdirectory 上传路径
    * @return success 成功 error失败
    */
    public static Map<String, String> saveMultFile(MultipartFile file, String subdirectory) {
    String path = GetServerPathUtil.getPath(subdirectory);// 上传文件路径
    String originalFilename = file.getOriginalFilename();//  获取文件名称
    String fielhouzhui = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
    // 重新修改文件名防止重名
    String filename = new SimpleDateFormat("yyyyMMddHHmmssSSS")
    .format(new Date())
    + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000) + StringUtils.getUUID() + fielhouzhui;
    File filepath = new File(path, filename);
    // 判断路径是否存在,没有就创建一个
    if (!filepath.getParentFile().exists()) {
    filepath.getParentFile().mkdirs();
    }
    // 将上传文件保存到一个目标文档中
    Map<String, String> map = new HashMap<>();
    File file1 = new File(path + File.separator + filename);
    try {
    file.transferTo(file1);
    map.put("res", "success");
    map.put("url", filename);
    return map;
    } catch (IOException e) {
    map.put("res", "error");
    return map;
    }
    }

    4.图片上传并压缩

    需要导入以下jar包:

    <!-- 图片压缩 -->
    <dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
    </dependency>

    代码:

    /**
    * 图片上传并压缩
    *
    * @param file 文件
    * @param subdirectory 文件夹名称
    * @param width 图片宽度
    * @param height 图片高度
    * @return
    */
    public static Map<String, String> saveImgCompress(MultipartFile file, String subdirectory,Integer width,Integer height) {
    String path = GetServerPathUtil.getPath("uploadImg");//上传文件路径
    String filename = file.getOriginalFilename();// 获取文件名称
    String fielhouzhui = filename.substring(filename.lastIndexOf("."), filename.length());// 获取文件后缀名
    // 重新修改文件名防止重名
    filename = new SimpleDateFormat("yyyyMMddHHmmssSSS")
    .format(new Date())
    + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000) + StringUtils.getUUID() + fielhouzhui;
    File filepath = new File(path, filename);
    // 判断路径是否存在,没有就创建一个
    if (!filepath.getParentFile().exists()) {
    filepath.getParentFile().mkdirs();
    }
    File img = new File(path + File.separator + filename);
    Map<String, String> map = new HashMap<>();
    try {
    Thumbnails.of(file.getInputStream()).size(width,height).toFile(img);
    map.put("res", "success");
    map.put("url", filename);
    return map;
    } catch (IOException e) {
    log.info(filename + "图片上传失败:" + e);
    map.put("res", "error");
    return map;
    }
    }

    5.文件删除

    /**
    * 文件删除
    *
    * @param fileNmae 文件名字
    * @return
    */
    public static String delFile(String fileName,String subdirectory){
    // 获取存放路径
    String path = GetSerPathUtil.getPath(subdirectory);
    String resultInfo = null;
    File file = new File (sb);
    if(file.exists()){
    if(file.delete()){
    resultInfo = "1";// 删除成功
    }else{
    resultInfo = "1";// 删除失败
    }
    } else {
    resultInfo = "-1";// 文件不存在
    return resultInfo;
    }

    字符串常用方法:

    1.获取32位小写的UUID

    /**
    *  获取32位小写的UUID
    * @return 32位UUID
    */
    public static String getUUID() {
    return UUID.randomUUID().toString().replace("-", "");
    }

    2.获取32位大写的UUID

    /**
    *  获取32位大写的UUID
    * @return 32位UUID
    */
    public static String getUUIDStr() {
    return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }

    3.判断多个字符串是否为空

    /**
    * 判断多个字符串是否为空
    *
    * @param list 值 ("1","2"....)
    * @return true:为空 false:非空
    */
    public static boolean isAllStrEmpty(String... list) {
    // 判断数据是否为空
    for (String str : list) {
    if (StringUtils.isEmpty(str)) {
    return true;
    }
    }
    return false;
    }

    4.将下划线大小写字符转换为驼峰命名式

    /**
    * 将下划线大小写字符转换为驼峰命名式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
    *
    * @param str 转换前的下划线大写方式命名的字符串
    * @return 转换后的驼峰式命名的字符串
    */
    public static String convertToCamelCase(String str) {
    StringBuilder result = new StringBuilder();
    // 快速检查
    if (str == null || str.isEmpty()) {
    // 没必要转换
    return "";
    } else if (!str.contains("_")) {
    // 不包含下划线,仅首字母大写
    return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    // 用下划线将原始字符串分割
    String[] camels = str.split("_");
    for (String camel : camels) {
    // 跳过原始字符串开头、结尾的下划线或双重下划线
    if (camel.isEmpty()) {
    continue;
    }
    // 首字母大写
    result.append(camel.substring(0, 1).toUpperCase());
    result.append(camel.substring(1).toLowerCase());
    }
    return result.toString();
    }

    Http请求工具:

    1.GET请求

    /**
    * Get请求
    * @param urlStr
    *   请求的地址
    * @param parameter
    *   请求的参数 格式为:name=xxx&pwd=xxx
    * @param encoding
    *   服务器端请求编码。如GBK,UTF-8等
    * @return
    */
    public static String doGet(String urlStr, String parameter, String encoding) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
    url = new URL(urlStr);
    connection = (HttpURLConnection) url.openConnection();  // 新建连接实例
    connection.setConnectTimeout(2000);                     // 设置连接超时时间,单位毫秒
    connection.setReadTimeout(2000);                        // 设置读取数据超时时间,单位毫秒
    connection.setDoOutput(true);                           // 是否打开输出流 true|false
    connection.setDoInput(true);                            // 是否打开输入流true|false
    connection.setRequestMethod("Get");                     // 提交方法GET
    connection.setUseCaches(false);                         // 是否缓存true|false
    connection.connect();                                   // 打开连接端口
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
    out.writeBytes(parameter);                              // 写数据,也就是提交你的表单 name=xxx&pwd=xxx
    out.flush();                                            // 刷新
    out.close();                                            // 关闭输出流
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据 ,以BufferedReader流来读取
    StringBuffer buffer = new StringBuffer();
    String line = "";
    while ((line = reader.readLine()) != null) {
    buffer.append(line);
    }
    reader.close();
    return buffer.toString();
    } catch (IOException e) {
    // e.printStackTrace();
    System.err.println("MyHttpUtils==>通过url打开一个连接出现异常:" + e);
    LOG.error("MyHttpUtils==>通过url打开一个连接出现异常:" + e);
    } finally {
    if (connection != null) {
    connection.disconnect();// 关闭连接
    }
    }
    return null;
    }

    2.POST请求

    /**
    * Post请求
    * @param urlStr
    *   请求的地址
    * @param parameter
    *   请求的参数 格式为:name=xxx&pwd=xxx
    * @param encoding
    *   服务器端请求编码。如GBK,UTF-8等
    * @return
    */
    public static String doPost(String urlStr, String parameter, String encoding) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
    url = new URL(urlStr);
    connection = (HttpURLConnection) url.openConnection();  // 新建连接实例
    connection.setConnectTimeout(2500);                     // 设置连接超时时间,单位毫秒
    connection.setReadTimeout(2500);                        // 设置读取数据超时时间,单位毫秒
    connection.setDoOutput(true);                           // 是否打开输出流 true|false
    connection.setDoInput(true);                            // 是否打开输入流true|false
    connection.setRequestMethod("POST");                    // 提交方法POST
    connection.setUseCaches(false);                         // 是否缓存true|false
    connection.connect();                                   // 打开连接端口
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
    out.writeBytes(parameter);                              // 写数据,也就是提交你的表单 name=xxx&pwd=xxx
    out.flush();                                            // 刷新
    out.close();                                            // 关闭输出流
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据 ,以BufferedReader流来读取
    StringBuffer buffer = new StringBuffer();
    String line = "";
    while ((line = reader.readLine()) != null) {
    buffer.append(line);
    }
    reader.close();
    return buffer.toString();
    } catch (IOException e) {
    // e.printStackTrace();
    System.err.println("MyHttpUtils==>通过url打开一个连接出现异常:" + e);
    log.error("MyHttpUtils==>通过url打开一个连接出现异常:" + e);
    } finally {
    if (connection != null) {
    connection.disconnect();// 关闭连接
    }
    }
    return null;
    }

    密码加密:

    1.执行一次加密,两次解密

    /**
    * 加密解密算法 执行一次加密,两次解密
    *
    * @param inStr 字符串
    * @return
    */
    public static String convertMD5(String inStr) {
    char[] a = inStr.toCharArray();
    for (int i = 0; i < a.length; i++) {
    a[i] = (char) (a[i] ^ 't');
    }
    String s = new String(a);
    return s;
    }

    2.生成32位md5码

    /**
    * 生成32位md5码
    *
    * @param str 需要加密的字符串
    * @return 32位的md5码
    */
    public static String md5(String str) {
    return DigestUtils.md5Hex(str);
    }

    获取IP方法:

    IpUtils

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import javax.servlet.http.HttpServletRequest;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import java.nio.charset.StandardCharsets;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
    * 获取IP方法
    *
    * @author xiaofei
    */
    @Slf4j
    public class IpUtils {
    
    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php?ip=";
    
    /**
    * 获取客户端IP
    *
    * @param request
    * @return ip 客户端IP地址
    */
    public static String getIpAddr(HttpServletRequest request) {
    if (request == null) {
    return "unknown";
    }
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("X-Forwarded-For");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("X-Real-IP");
    }
    
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getRemoteAddr();
    }
    return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
    
    /**
    * 获取IP归属地
    *
    * @return
    * @throws Exception
    */
    public static Map<String, String> getIpAffiliation(HttpServletRequest req) {
    Map<String, String> map = new HashMap<>();
    // 获取ip地址
    String ip = IpUtils.getIpAddr(req);
    String address = "error";
    map.put("code", "0");
    // 内网不查询
    if (IpUtils.internalIp(ip)) {
    map.put("msg", "内网IP");
    return map;
    }
    // 判断是否为空
    if (StringUtils.isEmpty(ip)) {
    log.error("ip地址为空", ip);
    map.put("msg", "ip获取失败!");
    return map;
    }
    try {
    String url = IP_URL + ip;
    URLConnection urlConnection = new URL(url).openConnection();
    //打开与服务器的连接
    urlConnection.connect();
    StringBuilder stringBuilder = new StringBuilder();
    //读取服务器的响应
    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
    String line = null;
    while ((line = reader.readLine()) != null) {
    stringBuilder.append(line);
    }
    // 把数据解析为JSON
    JSONObject ipInfo = JSON.parseObject(stringBuilder.toString());
    JSONObject data = ipInfo.getJSONObject("data");
    map.put("code", "1");
    // 省份
    map.put("region",data.getString("region"));
    // 城市
    map.put("city",data.getString("city"));
    }catch (Exception e){
    log.error("获取ip省份出现异常", e);
    map.put("msg", "ip获取失败!");
    return map;
    }
    return map;
    }
    
    /**
    * 判断是不是内网Ip
    *
    * @param ip
    * @return
    */
    public static boolean internalIp(String ip) {
    byte[] addr = textToNumericFormatV4(ip);
    return internalIp(addr) || "127.0.0.1".equals(ip);
    }
    
    private static boolean internalIp(byte[] addr) {
    final byte b0 = addr[0];
    final byte b1 = addr[1];
    // 10.x.x.x/8
    final byte SECTION_1 = 0x0A;
    // 172.16.x.x/12
    final byte SECTION_2 = (byte) 0xAC;
    final byte SECTION_3 = (byte) 0x10;
    final byte SECTION_4 = (byte) 0x1F;
    // 192.168.x.x/16
    final byte SECTION_5 = (byte) 0xC0;
    final byte SECTION_6 = (byte) 0xA8;
    switch (b0) {
    case SECTION_1:
    return true;
    case SECTION_2:
    if (b1 >= SECTION_3 && b1 <= SECTION_4) {
    return true;
    }
    case SECTION_5:
    switch (b1) {
    case SECTION_6:
    return true;
    }
    default:
    return false;
    }
    }
    
    /**
    * 将IPv4地址转换成字节
    *
    * @param text IPv4地址
    * @return byte 字节
    */
    public static byte[] textToNumericFormatV4(String text) {
    if (text.length() == 0) {
    return null;
    }
    
    byte[] bytes = new byte[4];
    String[] elements = text.split("\\.", -1);
    try {
    long l;
    int i;
    switch (elements.length) {
    case 1:
    l = Long.parseLong(elements[0]);
    if ((l < 0L) || (l > 4294967295L))
    return null;
    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
    bytes[3] = (byte) (int) (l & 0xFF);
    break;
    case 2:
    l = Integer.parseInt(elements[0]);
    if ((l < 0L) || (l > 255L)) {
    return null;
    }
    bytes[0] = (byte) (int) (l & 0xFF);
    l = Integer.parseInt(elements[1]);
    if ((l < 0L) || (l > 16777215L)) {
    return null;
    }
    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
    bytes[3] = (byte) (int) (l & 0xFF);
    break;
    case 3:
    for (i = 0; i < 2; ++i) {
    l = Integer.parseInt(elements[i]);
    if ((l < 0L) || (l > 255L)) {
    return null;
    }
    bytes[i] = (byte) (int) (l & 0xFF);
    }
    l = Integer.parseInt(elements[2]);
    if ((l < 0L) || (l > 65535L)) {
    return null;
    }
    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
    bytes[3] = (byte) (int) (l & 0xFF);
    break;
    case 4:
    for (i = 0; i < 4; ++i) {
    l = Integer.parseInt(elements[i]);
    if ((l < 0L) || (l > 255L)) {
    return null;
    }
    bytes[i] = (byte) (int) (l & 0xFF);
    }
    break;
    default:
    return null;
    }
    } catch (NumberFormatException e) {
    return null;
    }
    return bytes;
    }
    }

    以后会继续完善!

    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: