**pinyin4j-2.5.0.jar**
package com.jalor.others;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class ConvertFileName {
public static void main(String[] args) {
System.out.println(toPinyin("嘉乐集团"));
}
public static String toPinyin(String fileString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = fileString.trim().toCharArray();
String output = "";
try {
for (int i = 0; i < input.length; i++) {
if (Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) { // 判断字符是否是中文
// toHanyuPinyinStringArray 如果传入的不是汉字,就不能转换成拼音,那么直接返回null
// 由于中文有很多是多音字,所以这些字会有多个String,在这里我们默认的选择第一个作为pinyin
String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
output += temp[0];
} else {
output += Character.toString(input[i]);
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
// Log.v(TAG, "BadHanyuPinyinOutputFormatCombination");
}
return output;
}
}
**扩展内容**
package com.jalor;
/**
* 阿拉伯数字与中文之间的转换
* @author <a href="mailto:lenian@syjalor.com">lenian</a>
* @version 2019年9月3日
*/
public class ABC {
public static void main(String[] args) {
System.out.println(toChinese("1001011"));
System.out.println(toChinese2("1008611"));
}
// 阿拉伯数字转成中文数字(¥)
private static String toChinese(String str) {
String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };
String result = "";
int n = str.length();
for (int i = 0; i < n; i++) {
int num = str.charAt(i) - '0';
if (i != n - 1 && num != 0) {
result += s1[num] + s2[n - 2 - i];
}
else {
result += s1[num];
}
}
return result;
}
// 将中文转换成阿拉伯数字
private static String toChinese2(String str) {
String[] s2 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
StringBuffer sb = new StringBuffer();
for (char c : str.toCharArray()) {
sb.append(s2[Integer.parseInt(String.valueOf(c))]);
}
return sb.toString();
}
}