简体   繁体   English

在 Java 中使用 PrintWriter 写入多行

[英]Writing multiple lines using PrintWriter in Java

I am sorry if this question is already answered on the internet but by looking at the 'similar questions' I couldn't find an answer for my problem.如果这个问题已经在互联网上得到回答,我很抱歉,但是通过查看“类似问题”,我找不到我的问题的答案。 So basically I'm trying to understand why using PrintWriter to write lines of text into a file apparently skips the first line every 2 lines I give.所以基本上我试图理解为什么使用 PrintWriter 将文本行写入文件显然每两行跳过第一行。

This is the method I use in its own class:这是我在自己的 class 中使用的方法:

public class IO_Utilities {

public static void Write(String outputName){

    PrintWriter outputStream = null;
    try {
        outputStream = new PrintWriter(outputName);
    } catch (FileNotFoundException e) {
        System.out.println(e.toString());
        System.exit(0);
    }
    System.out.println("Write your text:");
    Scanner user = new Scanner(System.in);
    while(!user.nextLine().equals("stop")) {
        String line = user.nextLine();
        outputStream.println(line);
    }
    outputStream.close();
    user.close();
    System.out.println("File has been written.");
}

When I call it from main with:当我从 main 调用它时:

IO_Utilities.Write("output.txt");

and write:和写:

first line
second line
third line
stop
stop

The output text is actually: output 文字实际上是:

second line
stop

I am sure the problem is the while loop, because if I input the lines manually one by one it works correctly, but I don't understand exactly why it behaves like it does right now.我确定问题出在 while 循环上,因为如果我一一手动输入行,它可以正常工作,但我不明白为什么它现在的行为如此。

while(!user.nextLine().equals("stop")) {
        String line = user.nextLine();
        outputStream.println(line);
    }

You repeat your user.nextLine();你重复你的user.nextLine(); within your loop, so line is not the same as the one you compare to "stop".在您的循环中,因此行与您比较“停止”的行不同。

Rewrite that part as:将该部分重写为:

String line = user.nextLine();
while( !line.equals("stop")) {
  outputStream.println(line);
  line = user.nextLine();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM