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

时间:2016-03-23 23:26:41

标签: 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

     

sdfjfjjjk

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

StringBuffer x = "ksjhbgkkgsjdjjnsfjsdfjfjjjk"

谢谢!

3 个答案:

答案 0 :(得分:0)

尝试使用以下内容:

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

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

答案 1 :(得分:0)

您可以将keyboard.nextLine()附加到stringBuffer,如下所示:

 lines.append(keyboard.nextLine());

StringBuffer将接受要追加的字符串,以便符合您的目的。

你可以将这个与while循环一起使用,如@Cache所示,它可以给出类似的东西:

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

答案 2 :(得分:0)

@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
}