Blnpwr
Blnpwr

Reputation: 1875

Java create multiple new files

I read this question here How to create a file in a directory in java?

I have a method that creates a QR Code. The method is called several times, depends on user input.

This is a code snippet:

String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);

The problem: If the user types "2" then this method will be triggered twice. As a result, the first qrCODE.png file will be replaced with the second qrCODE.png, so the first one is lost.

How can I generate more than one qr code with different names, like qrCODE.png and qrCODE(2).png

My idea:

if (!myFile.exists()) {
    try {
        myFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Any tips?

EDIT: I solved it by using a for loop and incrementing the number in the filename in every loop step.

Upvotes: 1

Views: 5142

Answers (3)

xxxvodnikxxx
xxxvodnikxxx

Reputation: 1277

You can create more files eg. like follows

int totalCount = 0; //userinput

String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";

for(int counter = 0; counter < totalCount; counter++){
    int size = 250;
    //tbd
    File myFile = new File(filePath+fileName+counter+"."+fileType);
    /*
       will result into files qrCODE0.png, qrCODE1.png, etc.. 
        created at the given location
    */
}

Btw to add check if file exists is also good point.

{...}
 if(!myFile.exists()){
    //file creation
    myFile.createNewFile()
 }else{
   //file already exists
 } 
{...}

Upvotes: 3

S.Tushinov
S.Tushinov

Reputation: 658

Your idea of solving the problem is a good one. My advice is to break up the filePath variable into a few variables in order to manipulate the file name easier. You can then introduce a fileCounter variable that will store the number of files created and use that variable to manipulate the name of the file.

int fileCounter = 1;
String basePath = "/Users/Test/";
String fileName = "qrCODE";
String fileType = ".png";

String filePath = basePath + fileName + fileType;
File myFile = new File(filePath);

You can then check if the file exists and if it does you just give a new value to the filePath variable and then create the new file

if(myFile.exists()){
    filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
    myFile = new File(filePath);
}
createFile(myFile);

And you're done!

Upvotes: 2

Ruslan
Ruslan

Reputation: 6300

You can check /Users/Test direcroty before create file.

String dir = "/Users/Test";
String pngFileName = "qrCode";

long count = Files.list(Paths.get(dir))      // get all files from dir
    .filter(path -> path.getFileName().toString().startsWith(pngFileName))   // check how many starts with "qrCode"
    .count();

pngFileName = pngFileName + "(" + count + ")";   

Upvotes: 2

Related Questions