簡體   English   中英

使用相對路徑保存我的二進制文件找不到該路徑

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

我想將數據存儲在一個二進制文件中,如果它不存在,它應該生成文件夾,但是事實並非如此,我在說,如果文件不存在,它應該生成它。

    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");
}

但是,它會產生以下錯誤

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)

我也不生成文件,這有點令人困惑。

您應該創建以下文件夾:

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

我將看一下代碼中“}”的位置。 似乎println超出了Try ... Catch塊。 那就是為什么您看到文本和錯誤的答案。 關於消息順序的第二個問題是,System.out和System.err在不同的時間寫,因為它們就像不同的線程。 因此,前兩行是System.out,同時堆棧跟蹤來自e.printStackTrace。

這個問題還回答了如何創建路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM