java 将字符串转换为 UUID 格式的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25895225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert String to UUID formatted string
提问by Paramesh Korrakuti
Is there any utility method available to convert plain string to UUID formatted string?
是否有任何实用方法可以将纯字符串转换为 UUID 格式的字符串?
For example:
例如:
Plain String:f424376fe38e496eb77d7841d915b074
纯字符串:f424376fe38e496eb77d7841d915b074
UUID formatted String:f424376f-e38e-496e-b77d-7841d915b074
UUID 格式字符串:f424376f-e38e-496e-b77d-7841d915b074
I just wanted to convert to UUID format without using any java logic, hence looking for predefined utility available in java.lang, java.util or Apache, etc packages.
我只是想在不使用任何 java 逻辑的情况下转换为 UUID 格式,因此在 java.lang、java.util 或 Apache 等包中寻找可用的预定义实用程序。
回答by Vladimír Sch?fer
You can simply use String.format
in the following way:
您可以String.format
通过以下方式简单地使用:
String plain = "f424376fe38e496eb77d7841d915b074";
String uuid = String.format("%1$-%2$-%3$-%4$", plain.substring(0,7), plain.substring(7,11), plain.substring(11,15), plain.substring(15,20));
Or with more library methods using Apache Commons Codec (org.apache.commons.codec.binary.Hex class) and JDK (java.util.UUID class):
或者使用 Apache Commons Codec(org.apache.commons.codec.binary.Hex 类)和 JDK(java.util.UUID 类)的更多库方法:
byte[] data = Hex.decodeHex("f424376fe38e496eb77d7841d915b074".toCharArray());
String uuid = new UUID(ByteBuffer.wrap(data, 0, 8).getLong(), ByteBuffer.wrap(data, 8, 8).getLong()).toString();