简体   繁体   中英

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?

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 .

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 .

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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