java 中append()_Java Text.append方法代码示例

import org.apache.hadoop.io.Text; //导入方法依赖的package包/类

/**

* Read a line terminated by one of CR, LF, or CRLF.

*/

private int readDefaultLine(Text str, int maxLineLength, int maxBytesToConsume)

throws IOException {

/* We're reading data from in, but the head of the stream may be

* already buffered in buffer, so we have several cases:

* 1. No newline characters are in the buffer, so we need to copy

* everything and read another buffer from the stream.

* 2. An unambiguously terminated line is in buffer, so we just

* copy to str.

* 3. Ambiguously terminated line is in buffer, i.e. buffer ends

* in CR. In this case we copy everything up to CR to str, but

* we also need to see what follows CR: if it's LF, then we

* need consume LF as well, so next call to readLine will read

* from after that.

* We use a flag prevCharCR to signal if previous character was CR

* and, if it happens to be at the end of the buffer, delay

* consuming it until we have a chance to look at the char that

* follows.

*/

str.clear();

int txtLength = 0; //tracks str.getLength(), as an optimization

int newlineLength = 0; //length of terminating newline

boolean prevCharCR = false; //true of prev char was CR

long bytesConsumed = 0;

do {

int startPosn = bufferPosn; //starting from where we left off the last time

if (bufferPosn >= bufferLength) {

startPosn = bufferPosn = 0;

if (prevCharCR) {

++bytesConsumed; //account for CR from previous read

}

bufferLength = fillBuffer(in, buffer, prevCharCR);

if (bufferLength <= 0) {

break; // EOF

}

}

for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline

if (buffer[bufferPosn] == LF) {

newlineLength = (prevCharCR) ? 2 : 1;

++bufferPosn; // at next invocation proceed from following byte

break;

}

if (prevCharCR) { //CR + notLF, we are at notLF

newlineLength = 1;

break;

}

prevCharCR = (buffer[bufferPosn] == CR);

}

int readLength = bufferPosn - startPosn;

if (prevCharCR && newlineLength == 0) {

--readLength; //CR at the end of the buffer

}

bytesConsumed += readLength;

int appendLength = readLength - newlineLength;

if (appendLength > maxLineLength - txtLength) {

appendLength = maxLineLength - txtLength;

}

if (appendLength > 0) {

str.append(buffer, startPosn, appendLength);

txtLength += appendLength;

}

} while (newlineLength == 0 && bytesConsumed < maxBytesToConsume);

if (bytesConsumed > Integer.MAX_VALUE) {

throw new IOException("Too many bytes before newline: " + bytesConsumed);

}

return (int)bytesConsumed;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值