0

I'm writing a byte[] to file and read it. But why the byte[] is different between write and read? Here is my code:

import java.io.*;

public class test{
    public static void main(String argv[]){
        try{
            byte[] Write = "1234567812345678".getBytes();
            byte[] Read = new byte[16];

            File test_file = new File("test_file");
            test_file.mkdir();

            String path = new String(test_file.getAbsolutePath()+"\\"+"test.txt");
            File test_out = new File(path);
            test_out.createNewFile();

            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(test_out));
            out.write(Write);
            out.close();

            File test_in = new File(path);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(test_in));
            while(in.available()>0)
                in.read(Read);
            in.close();

            System.out.println(Write);
            System.out.println(Read);
        }catch ( Exception e ){
            e.printStackTrace();
        }
    }
}

And here is the output; the input and output are different:

[B@139a55 
[B@1db9742
CosmicGiant
  • 6,275
  • 5
  • 43
  • 58

2 Answers2

1

[B@139a55
[B@1db9742

Those are the outputs of printing a byte[] - it is a hashcode of the object. It has nothing do to with its actual content.

It only tells you that you are printing two different objects - their content could still be the same.

You should instead print the actual content of the byte array: What's the simplest way to print a Java array?

Community
  • 1
  • 1
luk2302
  • 55,258
  • 23
  • 97
  • 137
0

When you print a byte[] that way you are printing the JVM's object reference, not the contents of the array.

Try this:

System.out.println(Arrays.toString(Write));
System.out.println(Arrays.toString(Read));
Todd
  • 30,472
  • 11
  • 81
  • 89