0

I want to store data inside a binary file and it should generate the folders if it does not exist, this is not the case however it seems, i am calling that if the file doesn't exist it should generate it.

    public Account(int accountid, String name, String lastname, double balance, AccountState state) {
    this.name = name;
    this.lastname = lastname;
    this.accountID = accountid;
    this.balance = balance;
    this.state = state;


    try {
        accountfile = new File("./Clients/" + lastname + "/" + name + "/" + "BalanceInfo " + accountid + ".ACC");
    if(!accountfile.exists()) {
        accountfile.createNewFile();

    }

    fos = new FileOutputStream(accountfile);
    oos = new ObjectOutputStream(fos);

    oos.writeObject("balance: " + balance);
    oos.writeObject("state: " + state.toString().toLowerCase());

    } catch(IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

    System.out.println("Account sucessfully Created");
}

However, it generates the following error

The system cannot find the path specified
Account sucessfully Created
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at dinges.Account.<init>(Account.java:44)
at dinges.Main.main(Main.java:10)

I don't generate the files either, which is a bit confusing.

  • Relative paths to `.` - the "current working directory" - is not recommendable as it depends on the starting point (IDE, bat, double click). Use `System.getProperty("user.home") + "/..."` or such. – Joop Eggen Jul 21 '16 at 14:25
  • @JoopEggen I think i'll use just that, but if i export it as a runnable jar won't it just generate the folders where i put the jar? It seems easier to use that way. –  Jul 21 '16 at 14:33
  • Yes, when they simply double click the jar. Maybe I am opinionated. My practice is to prompt users and so on. – Joop Eggen Jul 21 '16 at 14:39

2 Answers2

1

You should create the folders:

 try {
        accountfile = new File("./Clients/" + lastname + "/" + name + "/" + "BalanceInfo " + accountid + ".ACC");
    if(!accountfile.exists()) {
        accountfile.getParentFile().mkdirs();
        accountfile.createNewFile();
    }
yamenk
  • 46,736
  • 10
  • 93
  • 87
  • Thank you very much! I forgot about it that the createNewFile does not generate the path also. –  Jul 21 '16 at 14:32
0

I will take a look where I have the "}" in the code. Seems that the println is out to the Try ... Catch block. That answer why you see the text and the error. The second question about the order of the messages, well, the System.out and the System.err write at different moment, since they are like different threads. so the first 2 lines are System.out in the meantime the stack trace comes from the e.printStackTrace.

This question also answer how to create the path.

Community
  • 1
  • 1
kszosze
  • 341
  • 4
  • 9