如何在Java中编写连续命名的文件?

发布于 2024-09-26 02:56:30 字数 164 浏览 1 评论 0原文

我有一种保存文件的方法,但我不知道如何保存具有连续名称的文件,例如 file001.txtfile002.txtfile003 .txt, filennn.text

我怎样才能实现这个目标?

I have a method for saving a File, but I don't know how to save files with consecutive names such as file001.txt, file002.txt, file003.txt, filennn.text

How can I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒与心事 2024-10-03 02:56:30

您可以使用以下代码行来创建文件名。

String filename = String.format("file%03d.txt", fileNumber);

然后,您只需使用该字符串来创建新文件:

File file = new File(filename);

以下代码将创建编号为 1 - 100 的文件:

for (int fileNumber = 1; fileNumber <= 100; fileNumber++) {
    String filename = String.format("file%03d.txt", fileNumber);
    File file = new File(filename);
}

或者,您将需要一个静态变量,每次创建新文件时都会递增该变量。

private static int fileNumber = 0;
public void createNewFile(){
    String filename = String.format("file%03d.txt", fileNumber++);
    File file = new File(filename);
}

You can use the following line of code to create the filenames.

String filename = String.format("file%03d.txt", fileNumber);

Then you will just use that string to create new files:

File file = new File(filename);

The following code will create files numbered 1 - 100:

for (int fileNumber = 1; fileNumber <= 100; fileNumber++) {
    String filename = String.format("file%03d.txt", fileNumber);
    File file = new File(filename);
}

Or, you will need to have a static variable that you increment every time you create a new file.

private static int fileNumber = 0;
public void createNewFile(){
    String filename = String.format("file%03d.txt", fileNumber++);
    File file = new File(filename);
}
痴情换悲伤 2024-10-03 02:56:30

如果文件已经存在,您可能需要跳过写入该文件。

这可以通过将以下代码放置在 Justin 'jjnguy' Nelson 提出的 for 循环的开头来轻松完成,例如:

if(new File(fileName).exists())
{
    continue;
}

It may be desirable for you to skip over writing to a file if it already exists.

This could be done easily by placing the following at the beginning of the for loop proposed by Justin 'jjnguy' Nelson, for example:

if(new File(fileName).exists())
{
    continue;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文