1、导入依赖
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
2、获取中文的拼音工具类实现
public class PinYinUtil {
/**
* This method is used to get pinyin of Chinese character
* @param chinese : Chinese character
* @param firstLetter : If this field is true,get the first letter of pinyin,else get all
* @param upper : if this field is true,get uppercase.else get lowercase
* @return
*/
public static String getPinYin(String chinese,boolean firstLetter,boolean upper){
char[] chineseArra = chinese.toCharArray();
HanyuPinyinOutputFormat hypyFormat = new HanyuPinyinOutputFormat();
if(upper){
hypyFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
}else{
hypyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
}
hypyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
String pinyin = "";
try{
if(firstLetter){
for(int i =0 ;i<chineseArra.length;i++){
/**
* Judge whether it is a Chinese character,
* if it is,then convert to pinyin,
* otherwise do not convert
*/
if(String.valueOf(chineseArra[i]).matches("[\u4e00-\u9fa5]+")){
pinyin += PinyinHelper.toHanyuPinyinStringArray(chineseArra[i],hypyFormat)[0].substring(0,1);
}else{
continue;
}
}
}else{
for(int i =0 ;i<chineseArra.length;i++){
if(String.valueOf(chineseArra[i]).matches("[\u4e00-\u9fa5]+")){
pinyin += PinyinHelper.toHanyuPinyinStringArray(chineseArra[i],hypyFormat);
}else{
continue;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return pinyin;
}
}