簡體   English   中英

Java讀取一個帶有多個換行符的文本輸入

[英]Java read one text input with multiple newline characters

我正在尋找一種讀取復制並粘貼到IDE或終端機/ cmd中的行的方法,以便BufferedReader即使遇到換行符('\\ n)也會讀取所有文本。 棘手的部分是,讀者將必須知道用戶已按下Enter鍵(這是換行符),但是它必須繼續讀取輸入字符串中的所有字符,直到到達最后一個'\\n'為止。

有什么方法可以做到這一點(例如使用InputStreamReader等)?

回答:

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

好吧,我在Stack Overflow上沒有看到這個,所以我想問一下,而且我不知道InputStreamReader是否可以工作...但是我想它可以。 因此,如果您想讀取包含一串換行符的文本,則必須使用InputStreamReader

這是一個實現Reader的類(該類實現了readablecloseable並具有一個方法( read(chBuf) ),該方法可讓您讀取緩沖字符(數組)chBuf的輸入流。我用來測試該代碼的代碼是如下:

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

這行得通... 它將打印輸入的文本一遍半。

我可以看到您已經在努力,所以我將告訴您我的意思。 當您需要從流中讀取時,這是一種非常常見的模式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM