[英]What's the difference between java.lang.String.getBytes() and java.nio.charset.CharsetEncoder.encode()?
I was reading through the source code of java.lang.String , specifically getBytes() : 我正在阅读java.lang.String的源代码,特别是getBytes() :
public byte[] getBytes(Charset charset) {
if (charset == null) throw new NullPointerException();
return StringCoding.encode(charset, value, offset, count);
}
However, I couldn't find the StringCoding.encode() method in the Java API. 但是,我在Java API中找不到StringCoding.encode()方法。 I'd like to be able to compare it with java.nio.charset.CharsetEncoder.encode() , since that class/method is referenced as an alternative in the String.getBytes() javadoc. 我希望能够与java.nio.charset.CharsetEncoder.encode()进行比较,因为该类/方法在String.getBytes()javadoc中被引用为替代方法。 How do I find the StringCoding class, and it's source code? 我如何找到StringCoding类及其源代码? And what is the difference between the respective .encode() methods? .encode()方法之间的区别是什么?
The difference is that with a CharsetEncoder
you can choose how to fail; 区别在于,使用CharsetEncoder
可以选择失败的方式。 this is the CodingErrorAction
class. 这是CodingErrorAction
类。
By default, String
's .getBytes()
uses REPLACE
. 默认情况下, String
的.getBytes()
使用REPLACE
。 Most uses of CharsetEncoder
however will REPORT
insead. 但是, CharsetEncoder
大多数用法都会在REPORT
。
You can see an example of CodingErrorAction
usage at the end of this page . 您可以在此页面结尾查看CodingErrorAction
用法示例。
One such example of REPORT
usage is in java.nio.file. REPORT
用法的一个此类示例在java.nio.file中。 At least on Unix systems, a pathname which you created from a String
will be encoded before it is written to disks; 至少在Unix系统上,从String
创建的路径名将在写入磁盘之前进行编码。 if the encoding fails (for instance, you use ö
and system charset US-ASCII), the JDK will refuse to create the file and you will be greeted with an (unchecked!) InvalidPathException
. 如果编码失败(例如,您使用ö
和系统字符集US-ASCII),则JDK将拒绝创建文件,并且会向您发送一个(未经检查!) InvalidPathException
。
This is unlike File
which will create who knows what as a file name, and one more reason to ditch it... 这与File
)不同,后者将创建谁知道文件名,以及放弃它的另一个原因...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.