java常用工具方法

1、解析字符串中路径变量

private static final AntPathMatcher MATCHER = new AntPathMatcher();

/**
 * 解析 topic 模板中的变量 例如 $SYS/brokers/${node}/clients/${clientid}/disconnected 中提取 node 和 clientid
 *
 * @param topicTemplate topicTemplate
 * @param topic         topic
 * @return 提取的变量
 */
 public static Map<String, String> extractTopicValue(String topicTemplate, String topic){
    String pattern = topicTemplate.replace("${", "{").replace("#{", "{");
    try {
         return MATCHER.extractUriTemplateVariables(pattern, topic);
    } catch (IllegalStateException e) {
         return Collections.emptyMap();
    }
 }
 public static void main(String[] args) {
    System.out.println(extractTopicValue("tlink/${productKey}/${deviceName}/**", "tlink/123/456/command/setProperty/post"));
 }

运行结果:

2、获取jar包运行时目录

package com.talkweb.twiot.iothub.utils;

import cn.hutool.core.util.URLUtil;
import lombok.experimental.UtilityClass;
import org.springframework.lang.Nullable;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@UtilityClass
public class PathUtil {

    /**
     * 获取jar包运行时的当前目录
     *
     * @return {String}
     */
    @Nullable
    public static String getJarPath() {
        try {
            URL url = PathUtil.class.getResource("/").toURI().toURL();
            return PathUtil.toFilePath(url);
        } catch (Exception e) {
            String path = PathUtil.class.getResource("").getPath();
            return new File(path).getParentFile().getParentFile().getAbsolutePath();
        }
    }

    @Nullable
    private static String toFilePath(@Nullable URL url) {
        if (url == null) {
            return null;
        }
        String protocol = url.getProtocol();
        String file = URLUtil.decode(url.getPath(), StandardCharsets.UTF_8);
        if (ResourceUtils.URL_PROTOCOL_FILE.equals(protocol)) {
            return new File(file).getParentFile().getParentFile().getAbsolutePath();
        } else if (ResourceUtils.URL_PROTOCOL_JAR.equals(protocol) || ResourceUtils.URL_PROTOCOL_ZIP.equals(protocol)) {
            int ipos = file.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
            if (ipos > 0) {
                file = file.substring(0, ipos);
            }
            if (file.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
                file = file.substring(ResourceUtils.FILE_URL_PREFIX.length());
            }
            return new File(file).getParentFile().getAbsolutePath();
        }
        return file;
    }

    public static void main(String[] args) {
        getJarPath();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值