views:

181

answers:

2

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?

+5  A: 

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);
}
jjnguy
or "file%03d.txt" to match the pattern in the question
Thilo
@Thilo, thanks!! I was trying to find that option.
jjnguy
and fileNumber should probably be static so we don't forget where we are from invocation to invocation.
Tony Ennis
mmm and what would fileNumber be?
Valeria
@Valeria, well, it depends how you need to number them. If you are creating the files in a loop, then you can use the loop variable. Updating the answer.
jjnguy
@Justin 'jjnguy' Nelson, the files are created every time I click a button, can that be named a loop?(sorry, I'm new with Java)
Valeria
@Valeria, you will want to use my second suggestion then. Keep the number of files created as a variable in the class where you are creating files.
jjnguy
I'd rather loop and check for existing files to make it re-entrant/safer.
Thilo
@Thilo, agreed. It depends what the files are for. It might be ok to over-write the files. But, if you cannot over-write files, then you should check to see how high you got last time, and start there.
jjnguy
I realize verbosity is the norm if you want to be taken seriously as a Java programmer because, well, verbosity rules but... How is that easier to read than *File file = new File( "file" + filenum.getAndIncrement() + ".txt")* ? Where *filenum* is an *AtomicInteger* because moreover your example isn't threadsafe?
Webinator
@Web, well, code I post on the site is generally meant to be educational, and not copy-pasted straight into production code. Your example is good, and readable. My code attempts to teach as well as follow the spec that the asker posted.
jjnguy
A: 

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;
}
Zéychin