栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > .Net

java获取生僻字

.Net 更新时间:发布时间: 百科书网 趣学号

字符串中的生僻字在传输和存储的过程中存在着各种各样的问题,为了便于传输和存储,我们通常会把这些生僻字转换为16进制编码进行传输和存储。

package com.dc.util;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.nio.charset.Charset;

import java.util.HashMap;

import java.util.Map;

public class RareWordUtil {

private static Map nameToValue;

private static Map valueToName;

private String fileName = "gbk.txt";

private String fileEncoding = "GBK";

private final String preFix = "■△";

private static final RareWordUtil cr_instance = new RareWordUtil();

private RareWordUtil() {

try {

init();

} catch (IOException e) {

System.out.println(e.getMessage());

}

}

public static RareWordUtil getInstance() {

return cr_instance;

}

@SuppressWarnings( { "static-access", "unchecked" })

private void init() throws IOException {

if (nameToValue != null && valueToName != null) {

return;

}

InputStream input = RareWordUtil.class.getResourceAsStream(fileName);

InputStreamReader inputsr = new InputStreamReader(input, Charset.forName(fileEncoding));

BufferedReader br = new BufferedReader(inputsr);

this.nameToValue = new HashMap();

this.valueToName = new HashMap();

String line = null;

while ((line = br.readLine()) != null) {

String ret = new String(line.getBytes(fileEncoding), fileEncoding);

String key = ret.substring(0, 1);

String value = ret.substring(line.length() - 4, line.length());

this.nameToValue.put(key, value);

this.valueToName.put(value, key);

}

}

@SuppressWarnings("static-access")

public String getRareWord(String value) {

StringBuffer sb = new StringBuffer();

int pos = -1;

while ((pos = value.indexOf(preFix)) != -1) {

sb.append(value.substring(0, pos));

String code = value.substring(pos + preFix.length(), pos + preFix.length() + 4);

String codeValue = this.valueToName.get(code);

sb.append(codeValue);

value = value.substring(pos + preFix.length() + 4, value.length());

}

sb.append(value);

return sb.toString();

}

@SuppressWarnings("static-access")

public String getHex(String name) {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < name.length(); i++) {

String value = this.nameToValue.get(name.substring(i, i + 1));

if (value == null) {

sb.append(name.substring(i, i + 1));

} else {

sb.append(preFix + value);

}

}

return sb.toString();

}

public static void main(String[] args) {

RareWordUtil cu = RareWordUtil.getInstance();

String name = "王喆昊";

name = cu.getHex(name);

System.out.println("Cent2Dollar(1) = " + name);

name = cu.getRareWord(name);

System.out.println("Cent2Dollar(1) = " + name);

}

}

代码中用的的txt文件见附件。

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/984921.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号