【问题标题】:Unexpected interaction with String and File与字符串和文件的意外交互
【发布时间】:2015-04-04 20:28:53
【问题描述】:

我有以下代码:

    if (e.getSource() == theView.addButton) {

            System.out.println("Add Button clicked");
            theView.setBotTextArea("Adding category...");

            File directory = new File(theModel.getDirectory() + theView.getCategoryNameInput());

            boolean isDirectoryCreated = directory.mkdir();

            if(isDirectoryCreated) { 

                System.out.println("Created new directory in: " + directory);

            } else if (directory.exists()) { 

                System.out.println("Category already exists!");

            }               

        }

这是ActionListenerActionPerformed() 方法的一部分。

private File directory = new File("C:/Users/Lotix/Desktop/TestFolder/");
public File getDirectory() { 

    return directory;

}

我希望这种方法能在所选目录中创建一个子文件夹。但是,出于某种我不知道的原因,它在我的桌面上完全创建了另一个文件夹,而不是 TestFolder

我尝试了theModel.getDirectory().toString() 并操作变量,但无济于事。我想出的解决方案是简单地在之间添加正斜杠 theModel.getDirectory()theView.getCategoryNameInput() 比如这样:

File directory = new File(theModel.getDirectory() + "/" + theView.getCategoryNameInput());

但是,当我将 File 变量与另一个 String 连接时,它工作得非常好。

什么给了?

【问题讨论】:

  • 我通读了一遍,但恐怕我还是不明白。您介意详细说明吗?
  • 我的意思是,不要连接字符串以从目录和文件名创建文件,而应该使用适当的文件构造函数:我链接到的构造函数,它将目录作为第一个参数,并且文件名作为第二个参数。
  • 我明白了。这非常方便。谢谢你帮助我。开始重建我的方法。

标签: java string file directory


【解决方案1】:

您在自己的桌面目录中创建的任何文件都会出现在您的桌​​面上。这就是文件夹的用途。

这与“与字符串和文件的交互”或 Java 无关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 2022-10-23
    • 2016-11-05
    • 1970-01-01
    • 2022-10-25
    • 2021-06-13
    • 1970-01-01
    相关资源
    最近更新 更多