Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

73
LINES

< > BotCompany Repo | #1014159 // ByteCountingLineReader SSCCE for StackOverflow

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Libraryless. Click here for Pure Java version (109L/1K).

!7

set flag LeanMode.

p {
  ByteCountingLineReader r = new(new ByteArrayInputStream(toUtf8("Hello\r\nWorld\n")));
  
  S line = null;
  do {
    long count = r.byteCount();
    line = r.readLine();
    System.out.println("Line at byte " + count + ": " + line);
  } while (line != null);
  
  r.close();
}

static class ByteCountingLineReader implements Closeable { 
  InputStream in;
  long _byteCount;
  int bufferedByte = -1;
  boolean ended;
  
  // in should be a buffered stream!
  ByteCountingLineReader(InputStream in) {
    this.in = in;
  }
  
  ByteCountingLineReader(File f) throws IOException {
    in = new BufferedInputStream(new FileInputStream(f), 65536);
  }
  
  String readLine() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (ended) null;
    while true {
      int c = read();
      if (ended && baos.size() == 0) null;
      if (ended || c == '\n') break;
      if (c == '\r') {
        c = read();
        if (c != '\n' && !ended)
          bufferedByte = c;
        break;
      }
      baos.write(c);
    }
    return fromUtf8(baos.toByteArray());
  }
  
  int read() throws IOException {
    if (bufferedByte >= 0) {
      int b = bufferedByte;
      bufferedByte = -1;
      return b;
    }
    int c = in.read();
    if (c < 0) ended = true; else ++_byteCount;
    return c;
  }
  
  long byteCount() {
    return bufferedByte >= 0 ? _byteCount-1 : _byteCount;
  }
  
  public void close() throws IOException {
    if (in != null) try {
      in.close();
    } finally { in = null; }
  }
  
  bool ended() { ret ended; }
}

Author comment

Posted at https://stackoverflow.com/questions/15092869/how-to-know-bytes-readoffset-of-bufferedreader?rq=1

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1014159
Snippet name: ByteCountingLineReader SSCCE for StackOverflow
Eternal ID of this version: #1014159/12
Text MD5: 8cbb17011896b4764e057a01a6b1387d
Transpilation MD5: 02b08f4a3dc953d0372068ac3485320a
Author: stefan
Category: javax / io
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-04-15 14:13:03
Source code size: 1668 bytes / 73 lines
Pitched / IR pitched: No / No
Views / Downloads: 366 / 888
Version history: 11 change(s)
Referenced in: [show references]