无法从字符串转换为字节数组 [英] Unable to convert from string to byte array

查看:75
本文介绍了无法从字符串转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making a wordcount program and i want to write the total number of words at the end of the file. As i'm using FileOutputStream i've to convert my string to Byte array. But i'm getting a compile time error. Please help me out with this.

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

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

and i'm getting compile time error like this:

错误:不兼容的类型:byte []无法转换为Byte []

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

而且我正在使用write方法并传递一个像这样的字节数组:

and also i'm using write method and passing a byte arraylike this:

fout.write(msg);

其中,fout是在附加模式下打开的fileoutputstream的对象.我收到这样的错误:

where fout is object of fileoutputstream opened in append mode. i'm getting error like this:

错误:找不到适合write(Byte [])的方法.

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

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

推荐答案

您正在犯菜鸟错误.您正在使用 Byte [] 来存储 String.getBytes()方法返回的字节. getBytes()方法返回原始字节数组,而不是字节对象.用左侧的 byte [] 替换 Byte [] .它将100%起作用.

You are doing a noob mistake. You are using Byte[ ] to store the returned bytes from String.getBytes() method. The getBytes() method returns a primitive byte array not a byte object. Replace Byte[ ] with byte[ ] on left hand side. It will 100% work.

这篇关于无法从字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆