我已经尝试过关于这个主题的旧线程,但没有一个解决方案似乎适合我。我试图写一个名为“receipt.txt”的.txt文件但是使用以下代码我什么都没得到。没有创建文件(显然文件中没有任何文件不存在)没有任何错误。
//Write to File
String fileName = "receipt.txt";
try{
PrintWriter writer = new PrintWriter(fileName);
writer.println("Thank you for shopping with us");
writer.println("Name: " + customerName);
writer.println("Returning Customer: " + previousCustomer );
writer.println("Phone: " + phoneNumber);
writer.println("Shirt Type: " + shirtType);
writer.println("Shirt Color: " + shirtColor);
writer.println("Shirt Material: " + shirtMaterial);
writer.println("Item Amount: " + itmAmt);
writer.println("Total Cost: " + fmt3.format(totalCostMsg));
writer.close();
writer.flush();
System.out.println("Receipt printed");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
答案 0 :(得分:3)
您的输出已写入名为fileName
替换
PrintWriter writer = new PrintWriter("fileName");
带
PrintWriter writer = new PrintWriter(fileName);
编辑:
显然你只是在错误的地方寻找文件,添加以下语句以查看它的创建位置:
System.out.println(new File(fileName).getAbsolutePath());
另请注意,close
,flush
的顺序不正确。首先应该调用flush
。
答案 1 :(得分:3)
PrintWriter writer = new PrintWriter("fileName");
应该是
PrintWriter writer = new PrintWriter(fileName);
,因为您已经定义了
String fileName = "receipt.txt";