在java中解码编码的Pound符号

Ani*_*r C 7 java

我们使用外部服务以CSV格式获取数据.我们正在尝试将数据写入响应,以便csv可以下载到客户端.不幸的是,我们正在以下面的格式获取数据.

Amount inc. VAT      Balance
£112.83             £0.0
£97.55              £0.0
£15.28              £0.0
Run Code Online (Sandbox Code Playgroud)

我们无法解码内容.有没有办法在java中解码£和显示£.

是否有任何String Utils可用于解码字符串.

Jon*_*oni 5

该文件似乎以UTF-8编码.你应该把它读作UTF-8.

如果您正在使用java.io.FileReader和公司,您应该打开FileInputStream并使用InputStreamReader而不是:

// Before: Reader in = new FileReader(file)
Reader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
Run Code Online (Sandbox Code Playgroud)

如果您正在使用其他方法来读取文件(可能是外部或内部类库?),请检查其文档是否允许指定用于读取文件的文本编码.

更新:如果你已经有类似mojibake的字符串£97.55并且无法修复它的读取方式,则一种重新编码方式是将字符串转换回字节并将字节重新解释为UTF-8.此过程不需要任何外部"StringUtils"或编解码器库; Java标准API足够强大:

String input = ...obtain from somewhere...;
String output = new String(input.getBytes(/*use platform default*/), "UTF-8");
Run Code Online (Sandbox Code Playgroud)


Ani*_*r C 2

问题: 当我们在字符串上使用 getBytes() 时,它会尝试使用默认编码器进行解码。一旦字符串被编码,如果我们使用默认解码器,解码可能无法正常工作。

解决方案:apache 的一个 StringUtils 将帮助我们在写回响应时解码这些字符。该类可在org.apache.commons.codec.binary包中找到。

String CSVContent = "/* CSV data */";
/**
 *  Decode the bytes using UTF8.  
 */
String decodedStr = StringUtils.newStringUtf8(CSVContent.getBytes("UTF-8"));
/**
 *  Convert the decoded string to Byte array to write to the stream  
 */
Byte [] content = StringUtils.getBytesIso8859_1(decodedStr);
Run Code Online (Sandbox Code Playgroud)

Maven 2.0 依赖项。

<dependency>
     <groupId>commons-codec</groupId>
     <artifactId>commons-codec</artifactId>
     <version>1.6</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

解决方案:两个

根据@Joni,使用标准 API 的更好解决方案:

content = CSVContent.getBytes("ISO-8859-1");
Run Code Online (Sandbox Code Playgroud)