gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:01:03 24 4
gpt4 key购买 nike

我正在制作一个字数统计程序,我想在文件末尾写下总字数。当我使用 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() 方法返回原始字节数组而不是字节对象。将左侧的 Byte[ ] 替换为 byte[ ]。它将 100% 起作用。

关于java - 无法从字符串转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38036726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com