无法从字符串转换为字节数组

Unable to convert from string to byte array

我正在制作一个字数统计程序,我想在文件末尾写下总字数。当我使用 FileOutputStream 时,我必须将我的字符串转换为字节数组。但是我遇到了编译时错误。请帮我解决这个问题。

Byte[] msg;
msg="Total Number of words are: ".getBytes();

我遇到这样的编译时错误:

error: incompatible types: byte[] cannot be converted to Byte[]

而且我正在使用 write 方法并传递一个字节数组,如下所示:

fout.write(msg);

其中 fout 是以附加模式打开的文件输出流的对象。我收到这样的错误:

error: no suitable method found for write(Byte[]).

我已经导入了java.io.*;

你犯了一个菜鸟错误。您正在使用 Byte[ ] 来存储从 String.getBytes() 方法返回的字节。 getBytes() 方法 returns 原始字节数组而不是字节对象。将左侧的 Byte[ ] 替换为 byte[ ]。它将 100% 有效。

基本类型byte和包装器class有区别Byte

您应该将代码更改为 byte[] msg = ...,因为 String#getBytes() returns byte 个原语数组