簡體   English   中英

PrintWriter不會寫入.txt文件

[英]PrintWriter wont write to .txt file

我曾嘗試查看有關該主題的舊主題,但似乎沒有一種解決方案適合我。 我試圖寫一個名為“ 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();
 }

您的輸出將寫入名為fileName的文件

更換

PrintWriter writer = new PrintWriter("fileName");

PrintWriter writer = new PrintWriter(fileName);

編輯:

顯然,您不是在錯誤的位置查找文件,請添加以下語句以查看在何處創建了文件:

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

另請注意, closeflush的順序不正確。 flush應首先調用。

PrintWriter writer = new PrintWriter("fileName");

應該

PrintWriter writer = new PrintWriter(fileName);

如您所定義

String fileName = "receipt.txt";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM