0

I am trying to write data to a binary file and am having difficulty. When I run this method I don't get any output to the file. Also when it comes to writing my "Date" object, I can't seem to find a write method that takes it as a parameter. The object consists of an int month, day, and year. How can I write it into a binary file properly?

Also, does "File" work for binary as well? I have only previously used it for regular .txt files and I'm not sure if it can be used the same way in this situation. Thanks!

Here is my write method:

private void writeBinary(){
    //String fileName = getUserInput();
    String fileTest = "BinaryMonster.bin";
    File file = new File(fileTest);
    DataOutputStream out;

    try{
       out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, true)));

       if(!(file.exists())){
           file.createNewFile();
           System.out.println("New file created...");
       }

       for(int i = 0; i < monsterAttacks.size(); i++){
           out.writeInt(monsterAttacks.get(i).getID());
           out.write(monsterAttacks.get(i).getDate()); //getting error
           out.writeUTF(monsterAttacks.get(i).getName() + monsterAttacks.get(i).getLocation() + monsterAttacks.get(i).getReporter());

       }

    } catch(IOException e) {
        e.printStackTrace();
    }
}
7
  • //getting error -- What error? Please show the full error message. Also, you appear to be writing mostly text to the file -- why not output the data as a text file such as a JSON or XML file? Or as a serialized file via ObjectOutputStream? Commented Nov 18, 2017 at 19:10
  • 1
    Also, you never close() or flush() the Stream. Commented Nov 18, 2017 at 19:11
  • out.writeLong(monsterAttacks.get(i).getDate().getTime()); Commented Nov 18, 2017 at 19:13
  • But even after you fix this, your code is broken as it will be very difficult for you to retrieve any usable data from this file as you've wired it. Commented Nov 18, 2017 at 19:14
  • Do you have any suggestions for me to fix it? @HovercraftFullOfEels Commented Nov 18, 2017 at 19:21

1 Answer 1

1

It is giving error because you are writing whole object of date into the file using DataOutputStream, which don't allow you to do that.

Write it in the form of String into the file. It will be better.

out.writeUTF(monsterAttacks.get(i).getDate().toString());

But if you want to save the whole object into the file, then you need to use ObjectOutputStream which write whole serialized objects into the file.

And it is better approach to flush and close the file.

out.flush();
out.close();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.