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

What should the JCA deployment descriptor (ra.xml) character encoding be?

浏览 JCA 1.7 specification I could only find in one of their examples on the Resource Adapter Deployment Descriptor 以下内容(第 13 章:消息流入 P 13-50): 此示例显示了 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));

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

FindBugs 只是警告您依赖默认系统编码,因此如果您的应用程序将由另一个国家/地区的另一个用户启动,您可能会得到意想不到的结果。最好明确指定要使用的编码。

在您的情况下,应从 XML 文件中提取实际编码。有几种方法可以得到它。一种方法是使用 XMLStreamReader,如 this 答案中所述。

据我所知,大多数人的 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()));