簡體   English   中英

針對Java中的大型輸入優化BufferedReader

[英]Optimizing BufferedReader for large input in java

我正在嘗試使用以下代碼從標准輸入中讀取一行大約200萬個字符的行:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();

對於上述輸入, s = in.readLine(); 行需要30分鍾以上才能執行。

有沒有讀取此輸入的更快方法?

不要嘗試逐行讀取,而是嘗試讀取字符緩沖區

試試這個

BufferedInputStream in = null;
try {
    in = new BufferedInputStream(new FileInputStream("your-file"));

    byte[] data = new byte[1024];
    int count = 0;

    while ((count = in.read(data)) != -1) {
      // do what you want - save to other file, use a StringBuilder, it's your choice
    }
} catch (IOException ex1) {
  // Handle if something goes wrong
} finally {
    if (in != null) {
      try {
        in.close();
      } catch (IOException ) {
        // Handle if something goes wrong
      }
    }
}

暫無
暫無

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

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