使用 Main 中的变量从方法写入文件
编程 65
我有来自我的主要变量,我想使用私有(private)(或公共(public)并不重要,我将它们保存在同一个类中)方法将它们写入文本文件。我已经完成了将它们从主文件写入文件......我只是不知道如何将变量从主文件调用到我的 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!");
}
}
我还需要弄清楚如何制作一个单独的方法来读回文件,但我想如果我能弄清楚这部分,我可以设计它。
-
您可以通过向方法添加参数来传递对象。如果您需要引用另一个类或方法中的某些内容,只需添加更多参数即可。
我建议您创建一个 Customer 对象,以便您可以将其作为单个实体而不是几十个参数传递。
你可以尝试这样的事情:public class FileWriteExample { public static void main(String[] args) { String fileName = "order.txt"; Customer customer; // Customer object... int itemCount; float totalCost; try { PrintWriter writer = new PrintWriter(fileName); writeToFile(writer, customer, itemCount, totalCost); writer.flush(); writer.close(); JOptionPane.showMessageDialog(null, "Receipt has been printed"); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(0); } } public static void writeToFile(PrintWriter writer, Customer customer, int itemCount, float totalCost) { Card card = customer.getCard(); try { writer.println("Thank you for ordering from Diamond Cards"); writer.println("Name: " + customer.getName()); writer.println("Returning Customer: " + customer.getReturn()); writer.println("Phone: " + customer.getPhone()); writer.println("Card Type: " + card.getType()); writer.println("Card Color: " + card.getColor()); writer.println("Card Coating: " + card.getCoating()); writer.println("Item Amount: " + itemCount); writer.println("Total Cost: " + fmt1.format(totalCost)); } catch (IOException e) { System.out.println("Error!"); } } }
2025-04-13 15:07:02