gpt4 book ai didi

java - 当前路径和输入文件

转载 作者:行者123 更新时间:2023-12-01 14:09:20 25 4
gpt4 key购买 nike

我正在编写一个相当简单的 Java 程序,我需要用户提供一些选项,使他们能够从文本列表中读取数据以进行数据比较。

我想做的是让他们能够简单地定义文件(如果该文件位于当前工作路径中),并假设如此,除非他们为文件提供单独的路径。我想使用相同的方法在它们定义的任何地方生成输出文件。

因此,我首先检查该文件是否存在(如果您没有定义完整路径,则该文件不起作用):

File f1 = new File(inputFile);
if(f1.exists())
System.out.println("Exists");
else if(!f1.exists())
{
System.out.println("Cannot find file " + inputFile);
System.exit(1);
}

所以我可以使用 new File(path/inputFile) 创建文件,但我可以很容易地打破它。

我希望他们能够执行以下任意操作:

program.exe -m -1 inputFile.txt outputFile.txt

program.exe -m -1 C:\Users\tmp\Desktop\inputFile.txt outputFile.txt

program.exe -m -1 inputFile.txt C:\outputFile.txt

关于我下一步可以在哪里进行的任何建议?

最佳答案

你可以尝试类似的事情

String currentUserPath = System.getProperty("user.dir")

获取运行应用程序的当前路径。然后您可以检查用户是否在 args[0] 上提供了完整路径,例如:

String inputPath = args[0];
inputPath = inputPath.trim().toLowerCase(); // as you are using windows case doesn't matter
if (!inputPath.startsWith("c:"))
inputPath = currentUserPath + inputPath;

你可以对输出文件做类似的事情

关于java - 当前路径和输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18663533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com