【问题标题】:PrintWriter is only printing out the first line of the text filePrintWriter 仅打印出文本文件的第一行
【发布时间】:2020-09-26 22:27:46
【问题描述】:

我希望程序将我拥有的文本文件的每一行保存到 String 中,并使用 PrintWriter 将 String 打印到另一个文本文件中。

        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 的工作原理。(可能以上所有...)

我希望得到反馈!

【问题讨论】:

    标签: java


    【解决方案1】:

    write对象读完整个内容之前不要关闭它

    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();**
    

    【讨论】:

    • 谢谢你,呃,它总是最小和最愚蠢的错误
    【解决方案2】:

    您是在告诉它在写入行后立即关闭。

    您想将 out.close 移到您的 while 循环之外,您可能也应该刷新流。

    你的英文代码基本上是这样写的:

    从标准输入打开扫描仪 为文件打开打印机

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

    printwriter关闭后,不能写入新数据,因为已经关闭了。

    【讨论】:

      【解决方案3】:

      不要关闭循环内的 PrintWriter。在 while 循环之后执行此操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-24
        • 2021-09-20
        • 1970-01-01
        相关资源
        最近更新 更多