Cannot see the contents of the array printed in co

2019-09-22 18:45发布

问题:

This question already has an answer here:

  • What's the simplest way to print a Java array? 32 answers
public RMI post(PrintStream stream, Object object)
{
try
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    ObjectOutputStream oos = new ObjectOutputStream(baos);

    //

    oos.writeObject(System.rmi);

    oos.flush();

    oos.close();

    //

    stream.println("Class size: " + baos.toByteArray().length);

    stream.println("Class data: " + baos.toByteArray());

    stream.flush();

    stream.close();

    //
}
catch (Exception e)
{
    e.printStackTrace();
}

return this;

}

This prints [B@12843fce instead of the expected underlying bytecode structure. The same operation works find with FileOutputStream but here not with ByteArrayOutputStream. We would really need this to work. Can you spot what's wrong or what's happened?

回答1:

Don't print the reference to the object, you need a proper way to translate the byte[] to a String, and a common way is Arrays.toString(baos.toByteArray()).