简体   繁体   中英

How can I output a new text file every time my program runs?

I would like to know how I can make the program output a new text file every time it runs. For example first run machineslot(1).txt, second run machineslot(2).txt, and so forth. Or, make the output file contain when the file was made.

File file = new File("MachineSlot.Txt"); 

    try(PrintWriter out = new PrintWriter(new FileWriter(file));) {

        for (int i = 0; i < winData.length; i++){ 

            if (winData[i][0] != 0.0) {

            out.printf("You won Machine %.0f. You won $%.2f. You have %.0f quarters which equals $%.2f %n", winData[i][0], winData[i][1], winData[i][2], winData[i][3]);

            }
        }

        for (int k = 0; k < plays.length; k++)
            out.println("You were able to play machine " + (k + 1) +" a total of "+ plays[k] + " times.");
    }//end of try.      

    catch(IOException error){
        System.out.println("Could not use the IO file");
    }//End catch

My solution to this is use file name and add timestamp to it.

File file = new File("MachineSlot_" + System.currentTimeMillis() + ".txt");

Typically speaking any two files generated will have different time stamp of file generation. Avoid multiple check of existing files.

Other addition is have a formatted date.

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
File file = new File("MachineSlot_" + formatter.format(new Date()) + ".txt");

You can try this before the PrintWriter code

File file;
int i = 0;
do{
    file = new File(String.format("MachineSlot(%d).Txt", i++));
}
while (file.exists());

According to Your problem, best way to add date and time with your file name

String date = new SimpleDateFormat("yyyMMddHHmmssSS").format(new Date());

here current date is converted into specific format then file name would be

File file = new File("MachineSlot" + date + ".txt");

output looks like(file name)-

MachineSlot20171012094424.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM