如果未使用JFileChooser,则访问Java项目中的默认文件
我正在为一个程序开发一个简单的GUI,该程序允许用户选择要运行的属性文件。我有一个JFileChooser,允许用户选择他们的属性文件。我想这样做,如果没有使用JFileChooser选择文件,则将使用在我的项目文件夹的根目录中找到的默认文件。然后,该文件将添加到一个列表如果未使用JFileChooser,则访问Java项目中的默认文件,java,user-interface,jfilechooser,Java,User Interface,Jfilechooser,我正在为一个程序开发一个简单的GUI,该程序允许用户选择要运行的属性文件。我有一个JFileChooser,允许用户选择他们的属性文件。我想这样做,如果没有使用JFileChooser选择文件,则将使用在我的项目文件夹的根目录中找到的默认文件。然后,该文件将添加到一个列表,与ProcessBuilder一起使用,以运行实际的程序。这个GUI最终将导出到一个可运行的jar文件中。但是,由于某些原因,我无法将默认文件添加到列表中,即使它位于根目录中;如果它存储在根目录中,我应该可以访问它。当我打印出
public void createCommand()
{
List<string> commands = new ArrayList<string>()
commands.add("cmd.exe");
commands.add("/k");
command.add("java");
command.add("-jar");
commands.add("\"" + filepathtojar + "\\" + "testjar.jar");
File user_default = new File("user.default.properties");
//user.default.properties is in the root directory of the project
String propertypath = getPropertyFilePath();
if(propertypath.isEmpty()) // nothing is chosen in the JFileChooser
{
commands.add("-c");
System.out.println("default file's path is: " + user_default.getAbsolutePath());
commands.add(user_default.getAbsolutePath());
}
else // if a file is chosen in the JFileChooser
{
commands.add("-c");
commands.add(propertypath);
}
ProcessBuilder testprocess = new ProcessBuilder(commands);
...
Etc.
}
在打印命令时,如果没有使用JFileChooser选择属性文件,则会显示以下内容:
[cmd.exe,/k,“java,-jar,testjar]
如果选择了属性文件,则命令如下所示:
[cmd.exe,/k,“java,-jar,testjar,-c,属性文件”]
我已经尝试将默认文件写入临时文件,并将该临时文件添加到列表testjar
之后添加,-c,properties\u file
如果propertyPath
不是空的,您发布的代码只会添加该部分。只需将else的内容添加到if语句中即可
if(propertypath.isEmpty()) // nothing is chosen in the JFileChooser
{
commands.add("-c");
System.out.println("default file's path is: " + user_default.getAbsolutePath());
commands.add(user_default.getAbsolutePath());
commands.add("-c");
commands.add(propertypath);
}
else // if a file is chosen in the JFileChooser
{
commands.add("-c");
commands.add(propertypath);
}
如果有帮助,请告诉我。getPropertyFilePath()有什么作用当您将其分配给字符串propertypath时返回?它将返回JFileChooser中所选属性文件的文件路径,即使在您按“取消”时也是如此?如果是这种情况,则需要检查int JFileChooser返回的内容。如果是“取消”的值,则应返回空字符串,而不是所选文件。不完全正确。您现在在第一个if语句中添加了两个
-c
标志。@Compass Ya,我已经重读了几遍这个问题,但我的答案不正确。忽略它。我的主要问题是,我似乎无法访问要添加到列表中的user.default.properties文件,尽管它位于我的根目录中,并且能够看到它的直接文件路径在testjar.jar条目之后,列表if(propertypath.isEmpty()) // nothing is chosen in the JFileChooser
{
commands.add("-c");
System.out.println("default file's path is: " + user_default.getAbsolutePath());
commands.add(user_default.getAbsolutePath());
commands.add("-c");
commands.add(propertypath);
}
else // if a file is chosen in the JFileChooser
{
commands.add("-c");
commands.add(propertypath);
}