可能重複:
Writing to a file without overwriting or appending如何在不覆蓋以前的數據的情況下創建多個java txt文件?
嗨,我創建一個執行數據並打印成txt文件的程序。我遇到的問題是每次運行該程序都會覆蓋我以前的txt文件。我不希望它覆蓋,也不想追加數據。我想創建一個新的txt文件,每次它產生它創建的日期或時間。請有人幫助我嗎?
這裏是我的代碼:
private static PrintWriter outFile;
/**
* @param args
*/
//Main Method
public static void main(String[] args) throws IOException
{
//creates the new file to be saved
outFile = new PrintWriter(new FileWriter("trilogy.txt"));
//Create a generator object to create random numbers
Random gen = new Random();
//Create a scanner object to scan user input.
Scanner scan = new Scanner(System.in);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
//get current date time with Date()
Date date = new Date();
outFile.println(dateFormat.format(date));
outFile.println();
//Prompts the user to input how many lock combinations he/she wants generated.
System.out.print ("Enter quantity: ");
int quantity = scan.nextInt();
int count = 1;
//Loop - Only numbers 1 - 5 are used
// Only five numbers are generated per one lock combination
for (int i = 0; i < quantity; i++)
{
int n1 = gen.nextInt(5)+1;
int n2 = gen.nextInt(5)+1;
int n3 = gen.nextInt(5)+1;
int n4 = gen.nextInt(5)+1;
int n5 = gen.nextInt(5)+1;
//While loop making sure that NO numbers are repeated
while (n2==n1)
{
n2 = gen.nextInt(5)+1;
}
while (n3==n2 || n3 == n1 || n3==n4||n3==n5)
{
n3 = gen.nextInt(5)+1;
}
while (n4 == n3 || n4 == n2 || n4 == n1||n4==n5)
{
n4 = gen.nextInt(5)+1;
}
while (n5== n1 || n5==n2 || n5==n3 || n5==n4)
{
n5 = gen.nextInt(5)+1;
}
//If statements that output the random lock combinations in different formats.
if (n1==1){
outFile.println ("(" + count +") " + (n1*10 +n2) +"-"+ (n3*10+n4)+"-"+n5);}
else if (n2==2){
outFile.println ("(" + count +") " + n2 + "-" + (n1*10 + n3)+ "-" + (n4*10+ n5));}
else if (n3==3){
outFile.println ("(" + count +") " + (n3*10 +n2) +"-"+ n1+ "-" +(n4*10+n5));}
else if (n4 == 4){
outFile.println ("(" + count +") " + (n4 +"-"+ (n2*100 +n3*10+n1)+"-"+n5));}
else
outFile.println ("(" + count +") " + (n5) +"-"+ (n2) +"-"+ (n3) + "-"+ (n4) +"-" +(n1));
count++;
//Spaces one line in between each lock combination
outFile.println();
}
outFile.close();
}
}
奇怪的是,這個問題被問不到一個小時前:http://stackoverflow.com/questions/11055695/writing-to-一個文件,而無需-覆蓋有或附加 –
這是一個重複的,但我更喜歡這個版本,原來的 – finnw