Unable to convert from string to byte array

2019-07-14 08:39发布

问题:

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