native2ascii工具的java代码实现 2007-12-10 Java
Jdk提供了 native2ascii.exe工具可以将中文转换为unicode编码,本文提供了Java版本的实现以便在java程序中使用。
/**
*
* @param nativeStr
* nativeStr
* @return unicode
* @since 1.0.0
*/
public static String native2ascii(final String nativeStr) {
StringBuffer ret = new StringBuffer();
if (nativeStr == null) {
return null;
}
int maxLoop = nativeStr.length();
for (int i = 0; i < maxLoop; i++) {
char character = nativeStr.charAt(i);
final int n127 = 127;
final int n4 = 4;
if (character <= n127) {
ret.append(character);
} else {
ret.append(”\\u”);
String hexStr = Integer.toHexString(character);
int zeroCount = n4 - hexStr.length();
for (int j = 0; j < zeroCount; j++) {
ret.append(’0′);
}
ret.append(hexStr);
}
}
return ret.toString();
}
/**
*
* @param asciiStr
* asciiStr
* @return nativeStr
* @since 1.0.0
*/
public static String ascii2native(final String asciiStr) {
if (asciiStr == null) {
return null;
}
StringBuffer retBuf = new StringBuffer();
int maxLoop = asciiStr.length();
for (int i = 0; i < maxLoop; i++) {
if (asciiStr.charAt(i) == ‘\\’) {
final int n5 = 5;
final int n6 = 6;
final int n16 = 16;
if (i < maxLoop - n5
&& (asciiStr.charAt(i + 1) == ‘u’ || asciiStr
.charAt(i + 1) == ‘U’)) {
try {
retBuf.append((char) Integer.parseInt(asciiStr
.substring(i + 2, i + n6), n16));
i += n5;
} catch (NumberFormatException e) {
retBuf.append(asciiStr.charAt(i));
}
} else {
retBuf.append(asciiStr.charAt(i));
}
} else {
retBuf.append(asciiStr.charAt(i));
}
}
return retBuf.toString();
}
/**
*
* @param fileName
* uniStr
* @return unicode without changing comment
* @throws IOException
* IOException
*/
public static String native2asciiWithoutComment(final String fileName)
throws IOException {
StringBuffer buf = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
boolean continueFlg = false;
String line = null;
while ((line = reader.readLine()) != null) {
if ((line.trim().startsWith(”#”) || line.trim().startsWith(”!”))
&& !continueFlg) {
buf.append(line);
} else {
if (line.endsWith(”\\”)) {
continueFlg = true;
} else {
continueFlg = false;
}
buf.append(PropertiesUtil.native2ascii(line));
}
buf.append(”\n”);
}
if (!fileName.endsWith(”\n”)) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}






