[英]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.