java 生成uuid

uuid 作为通用识别码,其java的实现版本如下 ,本文以 将url(https://blog.youkuaiyun.com/renyuanfang/article/details/86701148)转换成uuid为例,实现具体的代码实现

import java.util.UUID;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.io.IOException;

public class uuid_test {
    public static void main (String[] args) throws IOException{
        final Charset UTF8 = Charset.forName("UTF-8");
        String url = "https://blog.youkuaiyun.com/renyuanfang/article/details/86701148";
        UUID NAMESPACE = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
        byte[] input = url.getBytes(UTF8);
        long least = NAMESPACE.getLeastSignificantBits();
        long most = NAMESPACE.getMostSignificantBits();
        byte[] out = new byte[16 + input.length];
        ByteBuffer buffer = ByteBuffer.wrap(out).order(ByteOrder.BIG_ENDIAN);
        buffer.putLong(most);
        buffer.putLong(least);
        buffer.put(input);
        System.out.println(UUID.nameUUIDFromBytes(out).toString());
    }
}

python 的生成版本如下:https://blog.youkuaiyun.com/renyuanfang/article/details/90213667

### 如何在Java生成UUID #### 使用`java.util.UUID`类生成UUID 通过调用`UUID.randomUUID()`方法可以直接获取到一个随机的UUID对象。此方法返回的是带有连字符的标准格式字符串,如果不需要这些连字符,则可以通过简单的字符串操作去除它们。 ```java import java.util.UUID; public class UUIDGenerator { public static void main(String[] args) { // 获取带连字符的UUID UUID uuidWithHyphens = UUID.randomUUID(); System.out.println("原始UUID(含连字符): " + uuidWithHyphens); // 去除连字符后的UUID String uuidWithoutHyphens = uuidWithHyphens.toString().replace("-", ""); System.out.println("无连字符UUID: " + uuidWithoutHyphens); } } ``` 上述代码展示了两种形式的UUID输出:一种是包含了连字符的形式;另一种则是去除了所有连字符之后的结果[^1]。 #### 利用第三方库简化处理过程 对于更复杂的场景或者为了提高编码效率,也可以借助一些成熟的开源工具包来进行UUID的操作。例如Google Guava提供了方便的方法来移除特定字符: ```java import com.google.common.base.CharMatcher; import java.util.UUID; public class EnhancedUUIDGenerator { public static void main(String[] args) { UUID uuid = UUID.randomUUID(); // 使用CharMatcher移除指定字符'-' String cleanUUID = CharMatcher.is('-').removeFrom(uuid.toString()); System.out.println("清理后的UUID:" + cleanUUID); } } ``` 这段程序利用了Guava中的`CharMatcher`功能实现了更加简洁直观的方式去除连字符[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值