[英]Writing Multiple Lines of User Input to a File
I am trying to have the equivalent of a text box in console by reading the user's input until a certain terminator sequence is reached, but I cannot figure out how to get it to terminate. 我试图通过读取用户的输入,直到达到某个终止符序列,在控制台中拥有一个等效的文本框,但是我无法弄清楚如何使其终止。
Here the code that is supposed to read input and write it to the file: 这里应该读取输入并将其写入文件的代码:
try {
out = new BufferedWriter(new FileWriter("outagain.txt");
userInput = new Scanner(System.in);
String input;
while ((input = userInput.nextLine)) != null) {
out.write(input);
out.newLine();
input = null;
}
} finally {
if (userInput != null)
userInput.close();
if (out != null)
out.close();
Is there some way I can capture an escape "code" from the user (ie they write ":END" which breaks out of the loop) or is there another way to do it? 有什么方法可以捕获用户的转义“代码”(即,他们写出“:END”,它会跳出循环)还是有另一种方法?
Thank you in advance. 先感谢您。
You can do it by comparing each input line with the specific termination word. 您可以通过将每个输入行与特定的终止字进行比较来实现。 Suppose the termination word is :END
then we can check each input line with the termination word
. 假设终止词为:END
那么我们可以用termination word
检查每条输入线。
If we find that termination word as an input , We will break the loop and stop taking the input from user and close the BufferedReader
as well as the Scanner
. 如果我们发现该终止词作为输入,我们将中断循环并停止从用户那里获取输入,并关闭BufferedReader
和Scanner
。
Sample Code: 样例代码:
try
{
out = new BufferedWriter(new FileWriter("outagain.txt"));
userInput = new Scanner(System.in);
String input = userInput.nextLine(); //Store first input line in the variable
String Termination_Word = ":END";
while(!input.equals(Termination_Word)) //Everytime Check it with the termination word.
{
out.write(input); //If it isnot a termination word, Write it to the file.
out.newLine();
input=userInput.nextLine(); //Take other line as an input.
}
}
finally
{
if (userInput != null)
userInput.close();
if (out != null)
out.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.