Bytes.toBytes()与getBytes()区别
程序员文章站
2024-02-26 14:18:04
...
Bytes.toBytes()与getBytes()都用于将字符串转byte格式,区别如下
/**
* Converts a string to a UTF-8 byte array.
* @param s string
* @return the byte array
*/
public static byte[] toBytes(String s) {
return s.getBytes(UTF8_CHARSET);
}
以上为Bytes.toBytes()源码,可见仍然是调用了getBytes(),但是将转换完成的结果编码设为UTF-8
/**
* Encodes this {@code String} into a sequence of bytes using the given
* {@linkplain java.nio.charset.Charset charset}, storing the result into a
* new byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement byte array. The
* {@link java.nio.charset.CharsetEncoder} class should be used when more
* control over the encoding process is required.
*
* @param charset
* The {@linkplain java.nio.charset.Charset} to be used to encode
* the {@code String}
*
* @return The resultant byte array
*
* @since 1.6
*/
public byte[] getBytes(Charset charset) {
if (charset == null) throw new NullPointerException();
return StringCoding.encode(charset, value, 0, value.length);
}
而getBytes将会使用默认编码
上一篇: ubuntu下用户不能cd进~的解决方法
下一篇: 关于sed替换成回车符,两种方案
推荐阅读