bb2
bb2

Reputation: 2982

Writing a byte array to a file and looking at the file in java

I want to write a byte[] data to a file and I found this code:

public static void writeByte(String filename, byte[] data){

    BufferedOutputStream bos = null;

    try
    {
    //create an object of FileOutputStream
    FileOutputStream fos = new FileOutputStream(new File(filename));

    //create an object of BufferedOutputStream
    bos = new BufferedOutputStream(fos);


    /*
    * To write byte array to file use,
    * public void write(byte[] b) method of BufferedOutputStream
    * class.
    */
    System.out.println("Writing byte array to file");

    bos.write(data);

    System.out.println("File written");
    }
    catch(Exception fnfe)
    {
    System.out.println("exception");
    }
 }

This seems to work but I can't open the file to see the data...it says the "file is of an unknown type". Data was written because the file size is 25.5KB. My question is, how can I view the contents? Is there an extension that I have to use? Or do I need a special editor to open it? (Tried geany and gedit...)

Upvotes: 0

Views: 595

Answers (3)

user207421
user207421

Reputation: 311052

You don't need the BufferedOutputStream here at all, but you do need to close whichever stream you're using.

And when you catch an exception, don't just make up your own message. The exception itself contains three vital pieces of information: its class, its message, and its stack trace. Your own message by contrast contains basically one bit of information: it happened. You should always log or print the actual exception class and its message, and in cases of debugging difficulty its stacktrace too.

Upvotes: 0

Richard Povinelli
Richard Povinelli

Reputation: 1439

Use a hex file editor to view the contents. Such as:

These are just the ones I use. They are not necessarily the best hex editors.

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68907

Try to flush(); and close(); the stream after writing the bytes to it. If you were trying to write a known file format, this might be problem: that the last buffer of bytes wasn't actually written to the file, which caused the file was "corrupt".

Otherwise, use a hex editor as Richard suggested to see the raw bytes of the file.

Upvotes: 3

Related Questions