简体   繁体   中英

Java read one text input with multiple newline characters

I'm looking for a way to read a line that is copied and pasted into an IDE or a terminal/cmd, such that a BufferedReader will read all of the text even when it encounters a newline character ('\\n). The tricky part is that the reader will have to know that the user has pressed enter (which is a newline), but it has to keep reading all of the characters in the input string until it has reached the last '\\n' .

Is there any way to do this (such as with an InputStreamReader or something)?

ANSWER:

public static void main(String[] args) {
    InputStreamReader reader = new InputStreamReader(System.in);
    StringBuilder sb = new StringBuilder();

    int ch;

    System.out.println("Paste text below (enter or append to text \"ALT + 1\" to exit):");

    try {
        while ((ch = reader.read()) != (char)63 /*(char)63 could just be ☺*/) {
            sb.append(ch);
        }
        reader.close();
    }catch (IOException e) {
        System.err.println(e.toString());
    }
    String in = sb.toString();
    System.out.println(in);
}

Well, I didn't see this on Stack Overflow, so I thought I would ask, and I didn't know if InputStreamReader would work... but I guess it does. So, if you ever want to read text that has a bunch of newline characters, you have to use InputStreamReader .

This is a class implements Reader (which implements readable and closeable and has a method ( read(chBuf) ) that allows you to read an input stream to the buffer characters (an array), chBuf. The code that I used to test this is as follows:

public static void main(String[] args) {
    String in = "";

    InputStreamReader reader = new InputStreamReader(System.in);

    System.out.println("paste text with multiple newline characters below:");

    try {
        char chs[] = new char[1000];
        int n;
        while (reader.read(chs) != -1) {
            for (int i = 0; i < chs.length; i++) {
                char ch = chs[i];
                if (ch == '\u0000') {
                    break;
                } 
                in += chs[i];
            }
            System.out.println(in);
        }
        System.out.print(".");
    } catch (IOException e) {
        System.err.println(e.toString());
    }

    System.out.println(in);
}

This works... sort of. It prints the inputted text one and a half times.

I can see you've made an effort, so I'll show you what I mean. This is a pretty common pattern when you need to read from a stream:

char[] buffer = new char[1000];
StringBuilder sb = new StringBuilder();
int count;
// note this loop condition
while((count = reader.read(buffer)) != -1) {
    sb.append(buffer, 0, count);
}
String input = sb.toString();

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