2017-10-12 82 views
0

我想知道如何让程序在每次运行时输出一个新的文本文件。例如首先运行machineslot(1).txt,第二次运行machineslot(2).txt,等等。或者,在制作文件时使输出文件包含。每次我的程序运行时,如何输出新的文本文件?

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 
+0

为什么你需要PrintWriter? – Lokesh

+0

如果循环再次运行,你还想写一个不同的文件吗?或附加在现有的文件? – Lokesh

回答

2

我的解决方法是使用文件名,并添加时间戳它。

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

通常来说,任何生成的两个文件都会有不同的文件生成时间戳。避免对现有文件进行多重检查。

其他添加有一个格式化的日期。

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

伟大的这应该是解决方案。根据Jerry06的写法,它具有复杂性。假设有100个文件,所以循环将运行100次以生成新文件 – Lokesh

+1

是的,这一直都是有效的,你会注意到当我们重复生成日志/文件时,这会被使用很多次。 – Acewin

+0

@ Jerry06解决方案中最糟糕的部分是每次生成新文件时,时间复杂度都会不断增加 – Lokesh

1

您可以PrintWriter代码之前尝试这个

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

它是否满意**每次运行时新的文本文件** !!!? – 2017-10-12 03:37:49

+1

这是做什么是它添加一个数字到文件名。它会一直递增,直到你得到一个不存在的编号的文件为止。 – Acewin

+0

@ Jerry06太棒了! – 2017-10-12 03:45:45

0

根据您的问题,最好的方式来增加日期和时间与您的文件名

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

这里当前日期转换为特定的格式,那么文件名应为

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

输出看起来像(文件名) -

MachineSlot20171012094424.txt

相关问题