生成具有唯一名称的文件并将数据写入其中

generate files with unique names and write data into them

我想每次都将从数据库 table 中获取的数据写入具有不同名称的新文本文件。

我使用Calendar.getInstance().getTime()使文件名唯一并在所需目录中创建相应的新txt文件:

String path = "/home/username/Documents/Netbeans Projects/cashbackEngine/Reports";

Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmm");


SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormat.format(currentTime);
String reportFileName2 = "ICC_Cashback_Report_SS_$.txt".replace("$", sdf.format(currentTime));

String reportFilePath2 = path + "/" + reportFileName2;

File file = new File(reportFilePath2);
writer = new FileWriter(file, true); 

然后我遍历数据集并使用 writer.write();

将数据写入文件

是否有任何其他简单的方法来执行此操作...或 Java 中的任何内置字符串生成器方法自动生成具有固定前缀和唯一后缀编号的新文件名。

我不想用时间戳来区别其他的 每次执行 Java 代码时,新数据都会添加到新生成的文本文件中...

您可以使用简单的计数器作为文件前缀。但是,您必须在程序的不同运行之间保持计数器的当前状态,例如也在数据库中。这是 a question 处理相同问题的答案,包含您当前的方法和其他方法。