开发者

How can I write consecutive named files in Java?

I have a method开发者_如何学Python 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?


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);
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜