Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java PrintWriter仅打印文本文件的第一行_Java - Fatal编程技术网

Java PrintWriter仅打印文本文件的第一行

Java PrintWriter仅打印文本文件的第一行,java,Java,我希望程序将我拥有的文本文件的每一行保存到字符串s中,并使用PrintWriter将字符串s打印到另一个文本文件中 File htmltext = new File(filepath); Scanner file = new Scanner(htmltext); PrintWriter out = new PrintWriter("updated.txt");

我希望程序将我拥有的文本文件的每一行保存到字符串s中,并使用PrintWriter将字符串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();
我已经运行了代码并输出了.println,只是第一次输出了文本文件。 我查阅了如何将字符串打印到文本文件中,发现应该使用PrintWriter。 我希望程序基本上使用PrintWriter将文本文档的内容“重新打印”到“updated.txt”文件中。 然而,它似乎只是将文本文件的第一行“重新打印”到“updated.txt”中

我认为我的while循环有问题,所以我尝试使用System.out.println(s)定期将其打印到控制台中,但效果很好

我对while循环的理解是,虽然文件有标记,但它将迭代,s将存储一行,并且(它应该)打印所述字符串s

我错过了什么?我是否误解了while循环的工作原理?或者nextLine()是如何工作的?或者PrintWriter是如何工作的。(可能是以上所有的…)


我喜欢反馈

你告诉它写下这行代码后立即关闭

您想移出。靠近while循环的外部,您可能也应该刷新流

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

从标准输入打开扫描仪 打开文件的printwriter

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

printwriter关闭后,无法写入新数据,因为它已关闭。

不要在循环中关闭printwriter。在while循环之后执行此操作。

在完成整个内容的读取之前,不要关闭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();**

谢谢你,呃,这总是最小最愚蠢的错误