Search code examples
javabinaryfiles

Using a relative path for saving my binary file cannot find the path


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.


Solution

  • You should create the folders:

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