gpt4 book ai didi

java - 即使在 java 中进行存在检查也会创建输出文件

转载 作者:行者123 更新时间:2023-12-01 10:06:21 26 4
gpt4 key购买 nike

我目前正在 Java 中创建一个包,其中一个类包含创建和写入输出文件的方法。

我的目标是让该方法检查是否已创建输出文件。如果没有,请创建它。如果有,则不执行任何操作。通过创建输出文件,我想简单地将我在条件中指定的 sourceType 变量添加为实际文件名(不是整个路径)的前缀。

我的问题在于最后一句,因为尽管我进行了检查,但文件仍然被创建。如果我运行一次,我会从“/path/to/myFile”中获取“/path/to/FL_myFile”。如果我运行它两次,它会创建另一个名为“/path/to/FL_FL_myFile”的文件,这是错误的。

我已经连续编程了一段时间了,我的大脑已经很累了,所以如果这是一个愚蠢的错误,请原谅我......

非常感谢!

这是我的代码:

public static void RenameFiles(File subDir) {
File[] files = subDir.listFiles();
Path source = FileSystems.getDefault().getPath(subDir.toString());
String sourceType = null;
if (source.toString().endsWith("Flavonoid")) {
sourceType = "/FL_";
} else {
sourceType = "/SR_";
}
for (File file : files) {
Path oldFilePath = FileSystems.getDefault().getPath(file.toString());
Path newFilePath = FileSystems.getDefault().getPath(subDir.toString() + sourceType + file.getName());
File newFile = newFilePath.toFile();
if(newFile.exists()) {
System.out.println("Exists!!! Do nothing! : " + newFile.toString());
continue;
} else {
System.out.println("Does not exist!! Make it!! " + newFile.toString());
try {
Files.move(oldFilePath, newFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

感谢 Paul Ostrowski 的回答。正如所料,这是显而易见的,但我没有看到。在下面添加了一个简单的修复。

public static void RenameFiles(File subDir) {
File[] files = subDir.listFiles();
Path source = FileSystems.getDefault().getPath(subDir.toString());
String sourceType = null;
if (source.toString().endsWith("Flavonoid")) {
sourceType = "/FL_";
} else {
sourceType = "/SR_";
}
for (File file : files) {
Path oldFilePath = FileSystems.getDefault().getPath(file.toString());
Path newFilePath = FileSystems.getDefault().getPath(subDir.toString() + sourceType + file.getName());
File newFile = newFilePath.toFile();
if(file.getName().startsWith("SR_") || file.getName().startsWith("FL_")) {
continue;
} else {
System.out.println("Creating outfile: " + newFile.toString());
try {
Files.move(oldFilePath, newFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

最佳答案

您没有任何检查来确定文件是否以“FL_”或“SR_”开头。第一次运行时,foo.bar 会重命名为 FL_foo.bar。第二次运行时,foo.bar 不会被重命名,但已经存在的 FL_foo.bar 会被重命名为 FL_FL_foo.bar。您需要查看文件名是否以适当的“FL_”或“SR_”开头。

关于java - 即使在 java 中进行存在检查也会创建输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36437882/

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