【问题标题】:Using a relative path for saving my binary file cannot find the path使用相对路径保存我的二进制文件找不到路径
【发布时间】:2016-11-25 04:23:53
【问题描述】:

我想将数据存储在一个二进制文件中,如果它不存在它应该生成文件夹,但看起来情况并非如此,我呼吁如果文件不存在它应该生成它。

    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)

我也不生成文件,有点混乱。

【问题讨论】:

  • . 的相对路径 - “当前工作目录” - 不推荐,因为它取决于起点(IDE、bat、双击)。使用System.getProperty("user.home") + "/..." 之类的。
  • @JoopEggen 我想我会使用它,但如果我将它导出为可运行的 jar,它不会只生成我放置 jar 的文件夹吗?这种方式似乎更容易使用。
  • 是的,当他们只需双击 jar 时。也许我是固执己见。我的做法是提示用户等等。

标签: java binaryfiles


【解决方案1】:

我会看一下代码中“}”的位置。似乎 println 到了 Try ... Catch 块。这就是为什么您会看到文本和错误的答案。关于消息顺序的第二个问题,嗯,System.out 和 System.err 在不同的时刻写入,因为它们就像不同的线程。所以前两行是 System.out,同时堆栈跟踪来自 e.printStackTrace。

这个question也回答了如何创建路径。

【讨论】:

    【解决方案2】:

    您应该创建文件夹:

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

    【讨论】:

    • 非常感谢!我忘记了 createNewFile 也不会生成路径。
    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多