用于转换native2ascii的库,反之亦然 [英] Library for converting native2ascii and vice versa

查看:120
本文介绍了用于转换native2ascii的库,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索一个库(Apache / BSD / EPL许可),使用\ u将本机文本转换为ASCII,用于ASCII中不可用的字符(基本上是java.util.Properties所做的)。

I'm searching for a library (Apache / BSD / EPL licensed) to convert native text to ASCII using \u for characters not available in ASCII (basically what java.util.Properties does).

我看了一下,似乎没有任何现成的库。我发现:

I had a look and there don't seem to be any readily available libraries. I found:

  • JDK, tools.jar, native2ascii
  • Properties.saveConvert() (private method)
  • http://www.koders.com/java/fidD26ED81BEBE41932C405904AD53AEE8459BB8509.aspx (GPL)

是否有人知道上述许可证下的图书馆?

Is anyone aware of a library under the above stated licenses?

推荐答案

您可以使用CharsetEncoder执行此操作。您必须使用正确的编码来读取本机文本以进行unicode。您可以使用'US-ASCII'编码器来检测哪些字符将被转换为unicode转义。

You can do this with an CharsetEncoder. You have to read the 'native' Text with the correct encoding to unicode. Than you can use an 'US-ASCII'-encoder to detect, which characters are to be translated into unicode escapes.

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.junit.Test;

public class EncodeToEscapes {

@Test
public void testEncoding() {
    final String src = "Hallo äöü"; // this has to be read with the right encoding
    final CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder();
    final StringBuilder result = new StringBuilder();
    for (final Character character : src.toCharArray()) {
        if (asciiEncoder.canEncode(character)) {
            result.append(character);
        } else {
            result.append("\\u");
            result.append(Integer.toHexString(0x10000 | character).substring(1).toUpperCase());
        }
    }
    System.out.println(result);
 }
}

另外org.apache.commons:commons-lang包含StringEscapeUtils.escapeJava(),可以转义和转换本地字符串。

Additionally org.apache.commons:commons-lang contains StringEscapeUtils.escapeJava() which can escape and unescape native strings.

这篇关于用于转换native2ascii的库,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆