Unable to convert from string to byte array

拟墨画扇 提交于 2020-01-04 06:10:00

问题


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:

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

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

fout.write(msg);

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

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

I've imported java.io.*;


回答1:


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.




回答2:


There is a difference between the primitive type byte and the wrapper class Byte

You should change your code to byte[] msg = ... since String#getBytes() returns an array of byte primitives



来源:https://stackoverflow.com/questions/38036726/unable-to-convert-from-string-to-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!