如何使用命令控制台在java中输入文本



我想从文本处理器或其他处理器输入复制的文本。使用nextLine()只是引入了第一行,它不允许我也使用StringBuffer。我没有找到任何东西来解决我的问题。

这是我的代码:

public static void main (String args[]) {
    Scanner keyboard= new Scanner(System.in);
    StringBuffer lines= new StringBuffer();
    String line;
    System.out.println("texto:");
    line= keyboard.nextLine();
    //lines= keyboard.nextLine(); //this doesn´t work
    System.out.println(lines);
}

下面是我想做的一个例子:

我从文本文件中复制此文本:

ksjhbgkkg

sjdjjnsfj

sdfjjjk

然后,我把它粘贴到cmd上(我使用Geany)。我希望能够得到一个StringBuffer或类似的东西(我可以操作),如下所示:

StringBuffer x = "ksjhbgkkgsjdjjnsfjsdfjfjjjk"

谢谢!

尝试使用以下内容

while(keyboard.hasNextLine()) {
     line = keyboard.nextLine();
}

然后可以存储这些行。(例如数组/ArrayList)。

您可以将keypad.nextLine()附加到字符串缓冲区,如下所示:

 lines.append(keyboard.nextLine());

StringBuffer将接受要附加的字符串,因此这应该符合您的目的。

你可以将其与while循环一起使用,如@Cache所示,它会给出类似的结果:

 while (keyboard.hasNextLine()) {
      lines.append(keyboard.nextLine());
 }

@Cache Staheli有正确的方法。要详细说明如何将键盘输入输入到StringBuffer中,请考虑以下内容:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    StringBuffer lines= new StringBuffer();
    String line;
    System.out.println("texto:");       
    while(keyboard.hasNextLine() ) { // while there are more lines to read
        line = keyboard.nextLine();  // read the next line
        if(line.equals("")) {        // if the user entered nothing (i.e. just pressed Enter)
            break;                   // break out of the input loop
        }
        lines.append(line);         // otherwise append the line to the StringBuffer
    }
    System.out.println(lines);      // print the lines that were entered
    keyboard.close();               // and close the Scanner
}

最新更新