簡體   English   中英

PrintWriter 只打印出文本文件的第一行

[英]PrintWriter is only printing out the first line of the text file

我希望程序將我擁有的文本文件的每一行保存到 String s 中,並將帶有 PrintWriter 的 String s 打印到另一個文本文件中。

        File htmltext = new File(filepath);
        Scanner file = new Scanner(htmltext);
        
        PrintWriter out = new PrintWriter("updated.txt");
                
        while (file.hasNext()) {
            String s = file.nextLine(); 
            out.println(s);
            out.close();

我已經運行了代碼和 out.println(s),只打印了文本文件的第一次。 我查找了如何將字符串打印到文本文件中,我發現我應該使用 PrintWriter。 我期望程序基本上使用 PrintWriter 將文本文檔的內容“重新打印”到“updated.txt”文件中。 但是,它似乎只是將文本文件的第一行“重新打印”到“updated.txt”中。

我認為我的 while 循環出了點問題,所以我嘗試使用 System.out.println(s) 定期將其打印到控制台中,但效果很好。

我對 while 循環的理解是,雖然文件有標記,但它會迭代並且 s 將存儲一行並且(它應該)打印所述字符串 s。

我錯過了什么? 我誤解了while循環的工作原理嗎? 或者 nextLine() 是如何工作的? 或者 PrintWriter 是如何工作的。(可能以上所有...)

我希望得到反饋!

你告訴它一寫完行就關閉。

您想將 out.close 移到 while 循環之外,您也應該刷新流。

你的英文代碼基本上是這樣說的:

從標准輸入打開掃描儀打開文件的打印器

while the scanner has a new line
    write the new line to the printwriter
    **close the printwriter**

打印機關閉后,您無法寫入新數據,因為它已關閉。

不要在循環內關閉 PrintWriter。 在 while 循環之后執行此操作。

在讀完整個內容之前不要關閉對象

File htmltext = new File(filepath);
Scanner file = new Scanner(htmltext);
PrintWriter out = new PrintWriter("updated.txt");
while (file.hasNext()) 
{
String s = file.nextLine(); 
out.println(s);
}

**out.close();**

暫無
暫無

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

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