如何在Java中编写一个增加文件名的方法



我正在编写一个方法,该方法需要一个html字符串并将其写入文件。如果文件已经存在,该方法应该增加文件名。例如,如果wordmatch.html已经存在,那么应该创建一个新文件wordmatch1.html等等等等。

我已经创建了一个将html写入文件的方法。我正在做最后一部分,如果文件已经存在,则增量地更改新文件的名称。

public void saveContent(WordMatch wordMatch){
logger.info(wordMatch);
try {
File file = new File("wordmatch0.html");
String html = wordMatch.toString();
String cleanedHTML = html.replace("WordMatch(content=","").replace(")","");
logger.info(cleanedHTML);
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
try {
FileWriter myWriter = new FileWriter("word_match.html");
myWriter.write(cleanedHTML);
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
} else {
String fileName = file.getName().toString();
String index = fileName.substring(fileName.indexOf("h") + 1);
index = index.substring(0, index.indexOf("."));
Integer parsedInt = Integer.parseInt(index);
System.out.println(parsedInt);
parsedInt+=1;
fileName = fileName.replace(index,parsedInt.toString());
System.out.println(fileName);
System.out.println("fileName should have been printed by now");
file = new File(fileName);
FileWriter myWriter = new FileWriter(file);
myWriter.write(cleanedHTML);
myWriter.close();
//TODO add method to write file name with new index
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}

接下来我可以尝试什么?

一种简单的方法将计算文件的数量匹配你的文件名,然后增加numberOfFiles创建一个新文件名称:

Stream<Path> files = Files.list(Paths.get("C:\your\local\path"));
long numberOfFiles = files.map(Path.class::cast)
.filter(path -> path.getFileName().toString().startsWith("wordmatch"))
.count();

毕竟你必须管理某些情况,要有一个好的算法来管理你的文件。

这个问题看起来简单但有许多陷阱。

你写的算法不能工作,原因如下:

  1. 简单的if-else是不够的,您需要通过循环来找到最后一个索引,因为可能已经创建了许多文件。
  2. Else块尝试从文件名中找到一个不应该有索引的文件。

此外,还可能引起其他问题。

  • 如果有人删除了中间索引,现在你有1和4,你想要2还是5?
  • 有人可以删除目录中除程序以外的文件吗?
  • 嵌套目录可能吗?
  • 多长时间创建一次文件?
  • 有人可以手动创建一个具有适当名称的文件绕过程序吗?

和更重要的问题是——你真的想坚持严格的强力柜台实际文件中列出一个目录吗?

如果答案是肯定的,更合理的方法是使用file .list()检查文件,对它们排序,取最后一个索引并增加它们,而不是尝试创建一个文件并在失败时增加。

public class Main {
public static void main(String[] args) {
File directoryPath = new File("path_to_your_dir");
FilenameFilter filenameFilter = (dir, name) -> !dir.isFile();
Integer maxIndex = Arrays.stream(directoryPath.list(filenameFilter))
// Take numeric index from the end of the file name, beware of file extensions!
.map(name -> name.substring("word_match".length(), name.lastIndexOf('.')))
.map(Main::parseOrDefault) // Parse it to a number
.max(Integer::compareTo) // Define how to compare them
.orElse(-1);
// -1 is no files, 0 if a file with no index, otherwise max index
System.out.println(maxIndex);
}
private static Integer parseOrDefault(String integer) {
try {
return Integer.valueOf(integer);
} catch (NumberFormatException e) {
return 0;
}
}
}

如果答案是否定的,您可以有一个计数器,它被保存在某个地方(文件系统,BD),并且每次都递增。和更简单的方法就是建立一个文件创作和频数追加时间戳/日期-时间每个文件的结束。

最新更新