简体   繁体   English

PrintWriter不会写入.txt文件

[英]PrintWriter wont write to .txt file

I have tried reviewing old threads about this topic but none of the solutions seem to work for me. 我曾尝试查看有关该主题的旧主题,但似乎没有一种解决方案适合我。 I have trying to write to a .txt file named "receipt.txt" but with the following code I am getting nothing. 我试图写一个名为“ receipt.txt”的.txt文件,但是使用以下代码,我什么也没得到。 No file created (and obviously nothing in the file that doesn't exist) no errors just nothing. 没有创建文件(显然文件中不存在任何内容)没有错误,只是没有错误。

//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();
 }

Your output is writen to the file named fileName 您的输出将写入名为fileName的文件

replace 更换

PrintWriter writer = new PrintWriter("fileName");

with

PrintWriter writer = new PrintWriter(fileName);

EDIT: 编辑:

Apparenttly you are just not looking for the file in wrong place, add the following statement to see where it has bee created: 显然,您不是在错误的位置查找文件,请添加以下语句以查看在何处创建了文件:

System.out.println(new File(fileName).getAbsolutePath());

Also note that the order of close , flush is not correct. 另请注意, closeflush的顺序不正确。 flush should be called first. flush应首先调用。

PrintWriter writer = new PrintWriter("fileName");

should be 应该

PrintWriter writer = new PrintWriter(fileName);

as you have already defined 如您所定义

String fileName = "receipt.txt";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM