character-encoding - JCA 部署描述符 (ra.xml) 字符编码应该是什么?

标签 character-encoding xml-parsing findbugs jca deployment-descriptor

浏览JCA 1.7 specification我只能在资源适配器 Deployment Descriptor 上的一个示例中找到以下内容(第 13 章:消息流入 P 13-50): JCA DD example showing UTF-8 encoding 此示例显示 UTF-8 的用法编码,但是没有说明这是示例插图的可选选择还是对文件字符编码的必须限制。

我问这个是因为我正在编写一个 Java 程序来读取这些文件之一和 FindBugs™给我这条消息:

DM_DEFAULT_ENCODING: Reliance on default encoding Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.

此 Java 代码片段中的第 4 行是指定字符编码的位置:

01.  byte[] contents = new byte[1024];
02.  int bytesRead = 0;
03.  while ((bytesRead = bin.read(contents)) != -1)
04.     result.append(new String(contents, 0, bytesRead));

那么,在这种情况下是否可以指定该文件的预期编码?

最佳答案

据我所知,大多数人的 ra.xml 使用 UTF-8 编码。但是对于使用其他编码没有限制。因此,如果您的解析仅预期 UTF-8,则结果可能不会达到预期。

因此,当您将其作为普通文本阅读时,您要么需要在代码中对此进行计数,要么将其作为 xml 文件阅读,这样可以省去麻烦。我认为性能差异不会成为问题,因为 ra.xml 文件通常不会增长到千兆字节。至少到目前为止我见过的平均大小只有几兆字节。

对于 Findbug 问题,您只需将编码指定为 UTF-8 即可。否则,您将使用 JVM 的默认值,该默认值在虚拟机启动期间确定,通常取决于底层操作系统的区域设置和字符集。尽管这里不建议使用默认编码,但如果这是您想要的,那么只需指定默认编码的使用即可。这将消除 Findbug 问题。

所以你的代码看起来像这样:

01. byte[] contents = new byte[1024];
02. int bytesRead = 0;
03. while ((bytesRead = bin.read(contents)) != -1)
04.     result.append(new String(contents, 0, bytesRead, Charset.defaultCharset()));

关于character-encoding - JCA 部署描述符 (ra.xml) 字符编码应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30192455/

相关文章:

linux - 如何从文本文件中删除非 UTF-8 字符

javascript - 如何使用 javascript 将特殊的 UTF-8 字符转换为其等效的 iso-8859-1?

mysql - 在 Ubuntu 14.04 上读取 UTF-8 文件时发生 Flyway 错误 "Incorrect string value"

java - java中使用Dom解析xml

android - myParser.getText 总是返回 null

android - 在android项目上运行 Sonar : The class 'foo.bar.R$string' could not be matched to its original source file

hudson - Checkstyle 和 Findbugs 仅在 Jenkins(和/或 Hudson)上更改文件

java - 一次将字节解码为字符

python - 解析 PDF 时忽略表格

java - FindBugs 有争议的描述