如何使用Java中的Scanner从标准输入读取任意行数:

huangapple go评论72阅读模式
英文:

How to read an arbitrary amount of lines from standard input using Scanner in java

问题

import java.util.*;
import java.io.*;

public class ShoppingList {

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("参数数量无效。");
            return;
        }

        String outputFile = args[0];

        try {
            Scanner scanIn = new Scanner(System.in);
            File fileOut = new File(outputFile);
            PrintWriter myWriter = new PrintWriter(fileOut);
            fileOut.createNewFile();

            while (true) {
                String nextLine = scanIn.nextLine();
                if (nextLine.equals("")) {
                    break;
                }
                myWriter.write(nextLine + "\n");
            }
            myWriter.close();
        } catch (IOException e) {
            System.err.println("IOException");
            return;
        }
    }
}

我的代码在输入流的末尾和程序末尾之间会留下一个空行。链接 有没有办法去掉那行空行?谢谢!

英文:

I'm looking to scan standard input and write what is inputted into a file.

Currently, my code looks like this

import java.util.*;
import java.io.*;

public class ShoppingList {

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Invalid number of arguments.");
            return;
        }

        String outputFile = args[0];

        try {
            Scanner scanIn = new Scanner(System.in);
            File fileOut = new File(outputFile);
            PrintWriter myWriter = new PrintWriter(fileOut);
            fileOut.createNewFile();

            while (true) {
                String nextLine = scanIn.nextLine();
                if (nextLine.equals("")) {
                    break;
                }
                myWriter.write(nextLine + "\n");
            }
            myWriter.close();
        } catch (IOException e) {
            System.err.println("IOException");
            return;
        }
        
    }
}

Currently, my code leaves a blank line between the end of the input stream and the end of the program. Link Is there any way to get rid of that line? Thanks!

答案1

得分: 1

不要在将输入写入文件时在末尾添加换行符(\n),示例如下:

myWriter.write(nextLine + "\n");

而是应在将用户输入字符串添加到文件之前添加换行符。是的,这将在将第一行用户输入写入文件之前添加一个空行,因此您需要一种方法来确定是否已经将一行写入文件。有多种方法可以做到这一点,例如计数器、布尔标志等。

使用布尔标志:

public class ShoppingList {

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("参数数量无效。");
            return;
        }

        String outputFile = args[0];

        try {
            Scanner scanIn = new Scanner(System.in);
            File fileOut = new File(outputFile);
            java.io.PrintWriter myWriter = new java.io.PrintWriter(fileOut);
            fileOut.createNewFile();

            // 用于确定是否已经写入第一行的布尔标志。
            boolean firstLineWritten = false; 

            while (true) {
                String nextLine = scanIn.nextLine().trim();
                if (nextLine.equals("")) {
                    // 用户未提供内容 - 关闭文件。
                    break;
                }
                // 如果已经写入了第一行...
                if (firstLineWritten) {
                    // 在先前写入的文件行中添加系统换行符。
                    myWriter.write(System.lineSeparator());
                }
                // 将用户输入添加到文件(不添加换行符)
                myWriter.write(nextLine);
                // 立即将用户输入写入文件!
                myWriter.flush(); 
                // 标记第一行已经写入。
                firstLineWritten = true; 
            }
            myWriter.close();
        } catch (IOException e) {
            System.err.println("IOException");
        }
    }
}

使用计数器:

public class ShoppingList {

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("参数数量无效。");
            return;
        }

        String outputFile = args[0];

        try {
            Scanner scanIn = new Scanner(System.in);
            File fileOut = new File(outputFile);
            java.io.PrintWriter myWriter = new java.io.PrintWriter(fileOut);
            fileOut.createNewFile();

            // 用于确定是否已经写入第一行的计数器。
            int lineCounter = 0; 

            while (true) {
                String nextLine = scanIn.nextLine().trim();
                if (nextLine.equals("")) {
                    // 用户未提供内容 - 关闭文件。
                    break;
                }
                // 如果已经写入了第一行...
                if (lineCounter > 0) {
                    // 在先前写入的文件行中添加系统换行符。
                    myWriter.write(System.lineSeparator());
                }
                // 将用户输入添加到文件(不添加换行符)
                myWriter.write(nextLine);
                // 立即将用户输入写入文件!
                myWriter.flush(); 
                // 增加计数器以标记第一行已经写入。
                lineCounter++; 
            }
            myWriter.close();
        } catch (IOException e) {
            System.err.println("IOException");
        }
    }
}
英文:

Don't add the newline (\n) to the end of the input when you write to file such as:

myWriter.write(nextLine + "\n");

Instead add it to the file before you add the User input string to file. Yes, this would add a blank line before the first User input line is written to file so you need a means to determine if a line has already been written to the file. There are a number of ways you can do this, a counter, a boolean flag, etc.

Using a Boolean Flag:

public class ShoppingList {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Invalid number of arguments.");
return;
}
String outputFile = args[0];
try {
Scanner scanIn = new Scanner(System.in);
File fileOut = new File(outputFile);
java.io.PrintWriter myWriter = new java.io.PrintWriter(fileOut);
fileOut.createNewFile();
// Boolean Flag to determine if first line is written to file.
boolean firstLineWritten = false; 
while (true) {
String nextLine = scanIn.nextLine().trim();
if (nextLine.equals("")) {
// Nothing provided by User - Close the file.
break;
}
// If a first line has been written...
if (firstLineWritten) {
// Add a system line separator to the file line previously written.
myWriter.write(System.lineSeparator());
}
// Add User Input to file (no newline character added)
myWriter.write(nextLine);
// Write the User input to the file right away!
myWriter.flush(); 
// Flag the fact that the first line is written.
firstLineWritten = true; 
}
myWriter.close();
} catch (IOException e) {
System.err.println("IOException");
}
}
}

Using a Counter:

public class ShoppingList {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Invalid number of arguments.");
return;
}
String outputFile = args[0];
try {
Scanner scanIn = new Scanner(System.in);
File fileOut = new File(outputFile);
java.io.PrintWriter myWriter = new java.io.PrintWriter(fileOut);
fileOut.createNewFile();
// A counter to determine if first line is written to file. 
int lineCounter = 0; 
while (true) {
String nextLine = scanIn.nextLine().trim();
if (nextLine.equals("")) {
// Nothing provided by User - Close the file.
break;
}
// If a first line has been written...
if (lineCounter > 0) {
// Add a system line separator to the file line previously written.
myWriter.write(System.lineSeparator());
}
// Add User Input to file (no newline character added)
myWriter.write(nextLine);
// Write the User input to the file right away!
myWriter.flush(); 
// Increment counter to the fact that the first line is written.
lineCounter++; 
}
myWriter.close();
} catch (IOException e) {
System.err.println("IOException");
}
}
}

huangapple
  • 本文由 发表于 2020年9月11日 06:53:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63838651.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定