下面列出了java.nio.CharBuffer#rewind ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String[] parseLines(CharBuffer cb, Charset encoding) {
List<String> lines = new java.util.ArrayList<String>();
StringBuffer sb = new StringBuffer();
while (cb.hasRemaining()) {
while (cb.hasRemaining()) {
char c = cb.get();
if (c == '\n') {
break;
} else if (c == '\r') {
if (cb.hasRemaining()) {
c = cb.charAt(0);
if (c == '\n')
cb.get();
}
break;
} else {
sb.append(c);
}
}
lines.add(sb.toString());
sb.setLength(0);
}
cb.rewind();
return lines.toArray(new String[lines.size()]);
}
@Override
public char[] getPassword() {
byte[] bytes = null;
try {
bytes = Files.readAllBytes(passwordPath);
ByteBuffer bb = ByteBuffer.wrap(bytes);
CharBuffer decoded = Charset.defaultCharset().decode(bb);
char[] result = new char[decoded.limit()];
decoded.get(result, 0, result.length);
decoded.rewind();
decoded.put(new char[result.length]); // erase decoded CharBuffer
return result;
} catch (IOException e) {
throw new IllegalStateException("Could not read password from " + passwordPath + ": " + e, e);
} finally {
if (bytes != null) {
Arrays.fill(bytes, (byte) 0x0);
}
}
}
public static List<WifiConfiguration> loadConfigs(final File f) throws IOException {
if (!f.exists()) {
throw new FileNotFoundException("No such file");
}
CharBuffer cb = CharBuffer.allocate((int) f.length());
InputStreamReader isr = new InputStreamReader(
new BufferedInputStream(
new FileInputStream(f)), StandardCharsets.UTF_8);
isr.read(cb);
isr.close();
if (!f.delete())
Log.w(TAG, "Unable to delete file");
cb.rewind();
return loadConfigs(cb.toString());
}
public void testCodePoints() {
String s = "Hello\n\tworld";
CharBuffer cb = CharBuffer.allocate(32).append(s);
cb.rewind();
int[] expected = new int[s.length()];
for (int i = 0; i < s.length(); ++i) {
expected[i] = (int) s.charAt(i);}
assertTrue(Arrays.equals(expected, cb.codePoints().limit(s.length()).toArray()));
// Surrogate code point
char high = '\uD83D', low = '\uDE02';
String surrogateCP = new String(new char[]{high, low, low, '0'});
cb = CharBuffer.allocate(32).append(surrogateCP);
cb.rewind();
assertEquals(Character.toCodePoint(high, low), cb.codePoints().toArray()[0]);
assertEquals((int) low, cb.codePoints().toArray()[1]); // Unmatched surrogate.
assertEquals((int) '0', cb.codePoints().toArray()[2]);
}
public static void decodeReplace (byte[] input, char[] expectedOutput) throws CharacterCodingException {
ByteBuffer inputBB = ByteBuffer.wrap(input);
CharBuffer outputCB;
decoder.onMalformedInput(CodingErrorAction.REPLACE);
decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
outputCB = decoder.decode(inputBB);
outputCB.rewind();
assertEqualChars2("Decoded charactes must match!",
expectedOutput,
outputCB.array(),
input);
// assertTrue("Decoded charactes (REPLACEed ones INCLUSIVE) must match!",
// Arrays.equals(expectedOutput, outputCB.array()));
// assertEqualChars("Decoded charactes (REPLACEed ones INCLUSIVE) must match!",
// expectedOutput,
// outputCB.array());
// assertEquals("Decoded charactes must match!",
// String.valueOf(allChars),
// outputCB.toString());
}
private static void test(CharBuffer cb, String exp) {
cb.limit(cb.position());
cb.rewind();
if (!cb.toString().equals(exp))
throw new RuntimeException("expect: '" + exp + "'; got: '"
+ cb.toString() + "'");
cb.clear();
}
private static void test(CharBuffer cb, String exp) {
cb.limit(cb.position());
cb.rewind();
if (!cb.toString().equals(exp))
throw new RuntimeException("expect: '" + exp + "'; got: '"
+ cb.toString() + "'");
cb.clear();
}
public void NNtest_CodecDynamicIndividuals () throws CharacterCodingException {
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
decoder.onMalformedInput(CodingErrorAction.REPORT);
for (int code = 32; code <= 65533; code ++) {
if (encoder.canEncode((char) code)) {
// inputCB.rewind();
CharBuffer inputCB = CharBuffer.allocate(1);
inputCB.put((char) code);
inputCB.rewind();
ByteBuffer intermediateBB = encoder.encode(inputCB);
inputCB.rewind();
intermediateBB.rewind();
try {
CharBuffer outputCB = decoder.decode(intermediateBB);
outputCB.rewind();
assertEqualCBs("decode(encode(A)) must be identical with A = " + code,
inputCB, outputCB);
if (code == 165) {
outputCB.rewind();
System.out.println("WOW:" + outputCB.get());
}
} catch (CharacterCodingException e) {
fail("failed to decode(encode(" + code + "))");
}
}
}
}
private static void test(CharBuffer cb, String exp) {
cb.limit(cb.position());
cb.rewind();
if (!cb.toString().equals(exp))
throw new RuntimeException("expect: '" + exp + "'; got: '"
+ cb.toString() + "'");
cb.clear();
}
private static void checkIbmJdkWithBrokenUTF16(Charset charset){
if (!"UTF-16".equals(charset.name())) return;
final String TEST_STRING_2 = "v\u00e9s";
byte[] bytes = TEST_STRING_2.getBytes(charset);
final CharsetDecoder charsetDecoder2 = charset.newDecoder();
ByteBuffer bb2 = ByteBuffer.allocate(16);
CharBuffer cb2 = CharBuffer.allocate(TEST_STRING_2.length());
final int len = bytes.length;
for (int i = 0; i < len; i++) {
bb2.put(bytes[i]);
bb2.flip();
try {
charsetDecoder2.decode(bb2, cb2, i == (len - 1));
} catch ( IllegalArgumentException e){
throw new UnsupportedOperationException("UTF-16 requested when runninng on an IBM JDK with broken UTF-16 support. " +
"Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
}
bb2.compact();
}
cb2.rewind();
if (!TEST_STRING_2.equals(cb2.toString())){
throw new UnsupportedOperationException("UTF-16 requested when runninng on an IBM JDK with broken UTF-16 support. " +
"Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
};
}
public void testDecodeTrueIllegalState() throws CharacterCodingException {
ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 });
CharBuffer out = CharBuffer.allocate(100);
// Normal case: just created
decoder.decode(in, out, true);
in.rewind();
out.rewind();
// Normal case: just after decode with that endOfInput is true
decoder.reset();
decoder.decode(in, CharBuffer.allocate(30), true);
in.rewind();
decoder.decode(in, out, true);
in.rewind();
out.rewind();
// Normal case:just after decode with that endOfInput is false
decoder.reset();
decoder.decode(in, CharBuffer.allocate(30), false);
in.rewind();
decoder.decode(in, out, true);
in.rewind();
out.rewind();
// Illegal state: just after flush
decoder.reset();
decoder.decode(in, CharBuffer.allocate(30), true);
decoder.flush(CharBuffer.allocate(10));
in.rewind();
try {
decoder.decode(in, out, true);
fail("should illegal state");
} catch (IllegalStateException e) {
}
in.rewind();
out.rewind();
}
private MappeableArrayContainer(int newCard, CharBuffer newContent) {
this.cardinality = newCard;
CharBuffer tmp = newContent.duplicate();// for thread-safety
this.content = CharBuffer.allocate(Math.max(newCard, tmp.limit()));
tmp.rewind();
this.content.put(tmp);
}
private void decrementPath(CharBuffer path) {
int lastSlash = 0;
path.rewind();
for (int i = 0; i < path.limit(); i++) {
if (path.charAt(i) == '/') {
lastSlash = i;
}
}
path.limit(lastSlash);
}
private char[] getCharArray(CharBuffer cb) {
cb.rewind();
if (cb.hasArray()) {
return cb.array();
} else {
char[] chars = new char[cb.limit()];
cb.get(chars);
return chars;
}
}
/**
* Implementation of the encoding loop. Apply Perforce specific updates,
* then reset the encoder and encode the characters to bytes.
*/
protected CoderResult encodeLoop(CharBuffer cb, ByteBuffer bb) {
CharBuffer tmpcb = CharBuffer.allocate(cb.remaining());
while (cb.hasRemaining()) {
tmpcb.put(cb.get());
}
tmpcb.rewind();
update(tmpcb);
encoder.reset();
CoderResult cr = encoder.encode(tmpcb, bb, true);
cb.position(cb.position() - tmpcb.remaining());
return (cr);
}
private String readContent(final ODataResponse response) throws IOException {
CharBuffer content = CharBuffer.allocate(1000);
new InputStreamReader((InputStream) response.getEntity()).read(content);
content.rewind();
return content.toString();
}
public void testEncodeTrueIllegalState() throws CharacterCodingException {
CharBuffer in = CharBuffer.wrap("aaa");
ByteBuffer out = ByteBuffer.allocate(5);
// Normal case: just created
encoder.encode(in, out, true);
in.rewind();
out.rewind();
in.rewind();
out.rewind();
// Normal case: just after encode with that endOfInput is true
assertSame(encoder, encoder.reset());
encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
ByteBuffer.allocate(30), true);
encoder.encode(in, out, true);
in.rewind();
out.rewind();
// Normal case:just after encode with that endOfInput is false
assertSame(encoder, encoder.reset());
encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
ByteBuffer.allocate(30), false);
encoder.encode(in, out, true);
in.rewind();
out.rewind();
// Illegal state: just after flush
assertSame(encoder, encoder.reset());
encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
ByteBuffer.allocate(30), true);
encoder.flush(ByteBuffer.allocate(10));
try {
encoder.encode(in, out, true);
fail("should illegal state");
} catch (IllegalStateException e) {
}
// Normal case: after canEncode
assertSame(encoder, encoder.reset());
encoder.canEncode("\ud906\udc00");
encoder.encode(in, out, true);
in.rewind();
out.rewind();
assertSame(encoder, encoder.reset());
encoder.canEncode('\ud905');
encoder.encode(in, out, true);
}
public static CharBuffer reset(CharBuffer receiver) {
receiver.rewind();
return receiver;
}
public void testEncodeFacadeIllegalState() throws CharacterCodingException {
// encode facade can be execute in anywhere
CharBuffer in = CharBuffer.wrap("aaa");
// Normal case: just created
encoder.encode(in);
in.rewind();
// Normal case: just after encode facade
encoder.encode(in);
in.rewind();
// Normal case: just after canEncode
assertSame(encoder, encoder.reset());
encoder.canEncode("\ud902\udc00");
encoder.encode(in);
in.rewind();
assertSame(encoder, encoder.reset());
encoder.canEncode('\ud902');
encoder.encode(in);
in.rewind();
// Normal case: just after encode with that endOfInput is true
assertSame(encoder, encoder.reset());
encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
ByteBuffer.allocate(30), true);
encoder.encode(in);
in.rewind();
// Normal case:just after encode with that endOfInput is false
assertSame(encoder, encoder.reset());
encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
ByteBuffer.allocate(30), false);
encoder.encode(in);
in.rewind();
// Normal case: just after flush
assertSame(encoder, encoder.reset());
encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
ByteBuffer.allocate(30), true);
encoder.flush(ByteBuffer.allocate(10));
encoder.encode(in);
in.rewind();
}
private String readContent(final ODataResponse response) throws IOException {
CharBuffer content = CharBuffer.allocate(1000);
new InputStreamReader((InputStream) response.getEntity()).read(content);
content.rewind();
return content.toString();
}