寫入文件我有我的主要變量,並且我想使用一個私有(或公共並不重要,我保持它們在同一個類中)方法來編寫它們到一個文本文件。我已經完成了將它們寫入主文件...我只是無法弄清楚如何從main調用writeToFile()方法中的變量。以下是我所嘗試的,但我不知道如何將兩者結合起來。使用變量從主要的
//This portion is what I had in my main method that wrote the info to a file successfully
//Write to File
String fileName = "order.txt";
try{
PrintWriter writer = new PrintWriter(fileName);
writer.println("Thank you for ordering from Diamond Cards");
writer.println("Name: " + customerName);
writer.println("Returning Customer: " + customerReturn);
writer.println("Phone: " + custNumber);
writer.println("Card Type: " + customerType);
writer.println("Card Color: " + customerColor);
writer.println("Card Coating: " + customerCoat);
writer.println("Item Amount: " + numItems);
writer.println("Total Cost: " + fmt1.format(totalCostMsg));
writer.flush();
writer.close();
JOptionPane.showMessageDialog(null, "Receipt has been printed");
} catch (FileNotFoundException e)
{e.printStackTrace();
System.exit(0) ;
}
}
// This is where I try to create a method to do the file writing.... not sure how to proceed..
public static void writeToFile() {
try{
FileWriter fw = new FileWriter("order.text"); //File name to be created
PrintWriter pw = new PrintWriter (fw); // Prints to the file that was created
//text to be printed to file
// close the writer
pw.close();
// catch errors
} catch (IOException e) {
out.println("Error!");
}
}
我還需要弄清楚如何使一個單獨的方法來讀取文件回,但我想我可以工程師,如果我可以算出這個部分了。
只需在'writeToFile()'中添加所需的參數,以便您可以將它們傳入... –
這樣做? writeToFile(customerName,numItems,..... blah)? – user3537993