本文共 2291 字,大约阅读时间需要 7 分钟。
最近好奇,中文汉字怎么转换为中文拼音,在开源中国找到源码后,便开始了研究。
源码参考地址:, 谢谢这位作者。
下载好源码后,调用它的API进行测试,可以实现我要的功能。但是,很好奇,其数据来源于何处。打开源文件后,发现有三个db文件.如图
把jar包后缀名修改为zip后,尝试打开该.db文件,试了很多方法都没有,有通过sqlite打开,通过excel打开,都未能成功。
最后自己写程序,读取该文件内容,然后写入txt文件,终于看到了改文件的庐山真面。代码如下
资源读取类
package org.lor.pinyin;import java.io.IOException;import java.util.Properties;import java.util.logging.Level;import java.util.logging.Logger;import java.util.zip.ZipInputStream;/** * 资源文件加载类 * * @author Lor * @date 2014-8-12 * @version 1.0 * */public class PinyinResource { // 日志对象 protected static final Logger logger = Logger.getLogger(PinyinResource.class .getName()); /** * 获取资源属性 * * @param resourceName * 资源文件 * @return 属性对象 */ private static Properties getResource(String resourceName) { ZipInputStream zip = new ZipInputStream( PinyinResource.class.getResourceAsStream(resourceName)); try { zip.getNextEntry(); Properties p = new Properties(); p.load(zip); zip.close(); return p; } catch (IOException e) { logger.log(Level.WARNING, "IOException in loading PinyinResource", e); } return null; } /** * 获取拼音表属性 * @return */ protected static Properties getPinyinTable() { String resourceName = "/data/pinyin.db"; return getResource(resourceName); } /** * 获取多音字表属性 * @return */ protected static Properties getMultiPinyinTable() { String resourceName = "/data/mutil_pinyin.db"; return getResource(resourceName); } /** * 获取繁体简体字属性 * @return */ protected static Properties getChineseTable() { String resourceName = "/data/chinese.db"; return getResource(resourceName); } }文件写入测试类
package test;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.util.Properties;import org.lor.pinyin.PinyinResource;public class ReadPropertiesTest extends PinyinResource { public static void main(String[] args) throws IOException { Properties p = getChineseTable();//getMultiPinyinTable();//getPinyinTable() StringBuffer buffer = new StringBuffer(p.toString()); String charset = "UTF-8"; String file = "F:/chinese.txt"; FileOutputStream outputStream = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(outputStream,charset); try { writer.write(buffer.toString()); } finally { writer.close(); } }}最后可以看到三个文件的内容了。
截图如下