下面列出了怎么用java.io.PushbackReader的API类实例代码及写法,或者点击链接到github查看源代码。
/** Parser that eats everything until two consecutive dashes (inclusive) */
private void parseComment( PushbackReader in ) throws IOException, WrongDTDException {
int state = COMM_TEXT;
for( ;; ) {
int i = in.read();
if( i == -1 ) break; // EOF
switch( state ) {
case COMM_TEXT:
if( i == '-' ) state = COMM_DASH;
break;
case COMM_DASH:
if( i == '-' ) return; // finished eating comment
state = COMM_TEXT;
break;
}
}
throw new WrongDTDException( "Premature end of DTD" ); // NOI18N
}
@Test
public void testMatch() throws IOException {
String data = "C=c;B=&&B1=b1;A=&&A1=a1;A2=a2;A3=a3&&&&";
PushbackReader reader = new PushbackReader(new StringReader(data));
CharBuffer buffer = CharBuffer.allocate(10);
int len = ReaderStream.of(reader)
.next()
.when(c -> c =='=')
.then()
.next(2)
.when(c -> Arrays.equals(c,new char[]{'&','&'}))
.then(() -> {
System.out.print("is '=&&'");
})
.back()
.back()
.then(() -> {
System.out.print("is '='");
})
.done()
.read(buffer);
assertEquals(len,1);
}
public Map<String, String> deserialize(char[] data) throws IOException, T212FormatException {
PushbackReader reader = new PushbackReader(new CharArrayReader(data));
SegmentParser parser = new SegmentParser(reader);
parser.configured(segmentParserConfigurator);
Map<String,String> result = null;
try {
result = segmentDeserializer.deserialize(parser);
} catch (SegmentFormatException e) {
T212FormatException.segment_exception(e);
}
if(USE_VERIFICATION.enabledIn(verifyFeature)){
verifyByType(result);
}
return result;
}
@Override
public int[] executeBatch() throws SQLException {
long res = 0;
try {
CopyManager cpManager = ((PGConnection) connection).getCopyAPI();
PushbackReader reader = new PushbackReader(new StringReader(""),
batchBuilder.length());
reader.unread(batchBuilder.toString().toCharArray());
res = cpManager.copyIn("COPY " + tableName + " FROM STDIN WITH CSV", reader);
batchBuilder.setLength(0);
reader.close();
} catch (IOException e) {
throw new SQLException(e);
}
return new int[] { (int) res };
}
final boolean isLongTerminator(int terminator, PushbackReader r) throws IOException {
int c;
// look for terminator 2 - if it's not there put back what we saw
c = r.read();
if (c != terminator) {
r.unread(c);
return false;
}
// look for terminator 3 - otherwise put back what we saw and the
// preceeding terminator we found above
c = r.read();
if (c != terminator) {
r.unread(c);
r.unread(terminator);
return false;
}
// we found 3 in a row - now that's a long terminator
return true;
}
public void parse(Reader reader) throws JsonException {
pushbackReader = new PushbackReader(reader);
eventHandler.reset();
stack.clear();
char c;
while ((c = next()) != END_OF_STREAM) {
if (c == '{') {
readObject();
} else if (c == '[') {
readArray();
} else {
throw new JsonException(String.format("Syntax error. Unexpected '%s'. Must be '{'.", c));
}
c = assertNextIs(",]}");
if (c != END_OF_STREAM) {
pushBack(c);
}
}
if (!stack.isEmpty()) {
throw new JsonException("Syntax error. Missing one or more close bracket(s).");
}
}
boolean readToNextTag(PushbackReader r)
throws Exception
{
boolean foundATag = true;
try {
char c = readAndPushbackNextNonWhitespaceChar(r);
throwIfNotExpectedChar(c, '<', r);
} catch (Exception e) {
if (EOF.equals(e.getMessage())) {
foundATag = false;
} else {
throw e;
}
}
return foundATag;
}
private Row readLine(PushbackReader in) throws IOException {
Row ret=new Row();
while(true){
int c=in.read();
if(c<0) {
if(ret.size()>0) return ret;
else return null;
}
else in.unread(c);
Object v=readValue(in);
ret.add(v);
boolean next=readValueSeparator(in);
if(!next) break;
}
return ret;
}
private String parseString(PushbackReader in) throws IOException {
readWhitespace(in);
int c=in.read();
if(c!=stringChar) throw new RuntimeException("Error parsing CSV file");
StringBuilder sb=new StringBuilder();
while(true){
c=in.read();
if(c<0) throw new RuntimeException("Error parsing CSV file");
else if(c == stringChar) {
int c2=in.read();
if(c2==stringChar){
sb.append((char)stringChar);
}
else {
if(c2>=0) in.unread(c2);
return sb.toString();
}
}
else {
sb.append((char)c);
}
}
}
String readXMLName(PushbackReader r)
throws Exception
{
char c = readNextNonWhitespaceChar(r);
StringBuffer xmlName = new StringBuffer();
if (isXMLNameStartChar(c)) {
xmlName.append(c);
} else {
throwMessage("Error while reading XML name: " + c
+ " is not a valid start char.");
}
c = readNextChar(r);
while (isXMLNameChar(c)) {
xmlName.append(c);
c = readNextChar(r);
}
r.unread(c);
return xmlName.toString();
}
String readAttributeValue(PushbackReader r)
throws Exception
{
char c = readNextChar(r);
throwIfNotExpectedChar(c, '\"');
StringBuffer value = new StringBuffer();
c = readNextChar(r);
while (isXMLAttributeValueChar(c)) {
if (isXMLEscapeCharacter(c)) {
c = readEscapedCharacter(r);
}
value.append(c);
c = readNextChar(r);
}
throwIfNotExpectedChar(c, '\"');
return value.toString();
}
protected void throwIfNotExpectedChar(char c,
char expected,
PushbackReader pbr)
throws Exception
{
if (c != expected) {
StringBuffer msg = new StringBuffer();
msg.append("Expected " + expected + " but found " + c + "\n");
msg.append("At:");
for (int i = 0; i < 20; ++i) {
int rc = pbr.read();
if (rc == -1) {
break;
}
msg.append((char) rc);
}
throw new Exception(msg.toString()); // TODO
}
}
@Test
public void iteratorTest() {
String edn = "{:x 1} {:x 2}";
PushbackReader reader = new PushbackReader(new StringReader(edn));
Iterator<StreamingType> iterator = deserializeStream(reader, StreamingType.class).iterator();
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertEquals(1, iterator.next().x());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertEquals(2, iterator.next().x());
assertFalse(iterator.hasNext());
assertFalse(iterator.hasNext());
}
public TokenReplacingReader(final TokenResolver<Reader> resolver, final Reader source, final String start, final String end) {
if (resolver == null) {
throw new IllegalArgumentException("Token resolver is null");
}
if ((start == null || start.length() < 1) || (end == null || end.length() < 1)) {
throw new IllegalArgumentException("Token start / end marker is null or empty");
}
this.start = start;
this.end = end;
this.startChars = start.toCharArray();
this.endChars = end.toCharArray();
this.startCharsBuffer = new char[start.length()];
this.endCharsBuffer = new char[end.length()];
this.pushback = new PushbackReader(source, Math.max(start.length(), end.length()));
this.resolver = resolver;
}
public TokenReplacingReader(String source, Map<String, String> tokens, Deque<String> activeTokens,
Map<String, String> resolvedTokens) {
pushbackReader = new PushbackReader(new StringReader(source));
this.tokens = tokens;
this.activeTokens = activeTokens;
this.resolvedTokens = resolvedTokens;
}
public TreeReaderIterator(File file, Charset charset)
throws IOException {
//add by xpqiu
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(file), charset));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
// line = line.trim();
if(line.length()==0)
continue;
if(line.startsWith("<")&&line.endsWith(">"))
continue;
sb.append(line);
sb.append("\n");
}
in.close();
this.in = new PushbackReader(new StringReader(sb.toString()));
//end add
// this.in = new PushbackReader(new InputStreamReader(
// new FileInputStream(file), charset));
nextTree = nextTree();
}
/**
* Recursively lookup the longest key match.
* @param keyIn Where to read the key from
* @param pos The position in the key that is being
* looked up at this level.
* @return The Entry assocatied with the longest key
* match or null if none exists.
*/
Entry<T> getLongestMatch(PushbackReader keyIn, StringBuilder key) throws IOException
{
Node<T> nextNode;
Entry<T> ret;
int c;
char ch;
int prevLen;
// read next key char and append to key...
if((c = keyIn.read())<0)
// end of input, return what we have currently
return Entry.newInstanceIfNeeded(key,value);
ch = (char)c;
prevLen = key.length();
key.append(ch);
if((nextNode = getNextNode(ch))==null)
{ // last in trie... return ourselves
return Entry.newInstanceIfNeeded(key,value);
}
if((ret = nextNode.getLongestMatch(keyIn, key))!=null)
return ret;
// undo reading of key char and appending to key...
key.setLength(prevLen);
keyIn.unread(c);
return Entry.newInstanceIfNeeded(key,value);
}
/**
* Decode a metacharacter sequence.
*
* @param c the character after the backslash
* @param pb a PushbackReader representing the remainder of the region
* being processed (necessary for Unicode sequences)
*
* @return the decoded metacharacter, -1 on EOF, -2 for unknown or
* bad sequence
*
* @throws IOException read error
*/
private int decodeMetacharacter (int c, PushbackReader pb)
throws IOException
{
switch (c)
{
case 't':
c = '\t';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case METACHAR_SEQUENCE_START:
c = METACHAR_SEQUENCE_START;
break;
case 'u':
c = decodeUnicodeSequence (pb);
if (c == -2)
{
pb.unread ('u');
c = METACHAR_SEQUENCE_START;
}
break;
default:
// An escaped "regular" character is just the character.
break;
}
return c;
}
public void reset(Reader input) {
this.reader = new PushbackReader(new BufferedReader(input), 20);
currentSentence = null;
bufWord = new LinkedList<Word>();
bufSentence.setLength(0);
readedIdx = -1;
}
/** Parser that reads the markup type after <!. Recognizes ENTITY, ELEMENT
* and ATTLIST markup and forwards their processing to proper parser.
* It gets the control just after starting "<!" and releases after eating
* final '>' */
private void parseMarkup( PushbackReader in ) throws IOException, WrongDTDException {
StringBuffer sb = new StringBuffer();
for( ;; ) {
int i = in.read();
if( i == -1 ) throw new WrongDTDException( "Premature end of DTD" ); // NOI18N EOF
if( i == ' ' ) break;
sb.append( (char)i ); // next char of name
}
String markup = sb.toString();
switch (markup) {
case "ENTITY":
// NOI18N
parseEntityDefinition( in );
break;
case "ELEMENT":
// NOI18N
parseElement( in );
break;
case "ATTLIST":
// NOI18N
parseAttlist( in );
break;
default:
throw new WrongDTDException( "Wrong DTD markup <!" + markup );
}
}
public Table parse(InputStream inRaw, String encoding) throws IOException {
Table ret=new Table();
PushbackReader in=new PushbackReader(new InputStreamReader(inRaw,encoding),20);
Row row=null;
while( (row=readLine(in))!=null ){
ret.add(row);
}
return ret;
}
/** Reads a line and returns the char sequence for newline */
private static String readLine(PushbackReader r, StringBuffer nl) throws IOException {
StringBuffer line = new StringBuffer();
int ic = r.read();
if (ic == -1) return null;
char c = (char) ic;
while (c != '\n' && c != '\r') {
line.append(c);
ic = r.read();
if (ic == -1) break;
c = (char) ic;
}
if (nl != null) {
nl.append(c);
}
if (c == '\r') {
try {
ic = r.read();
if (ic != -1) {
c = (char) ic;
if (c != '\n') r.unread(c);
else if (nl != null) nl.append(c);
}
} catch (IOException ioex) {}
}
return line.toString();
}
private boolean compareText(PushbackReader source, String text) throws IOException {
if (text == null || text.length() == 0) return true;
text = adjustTextNL(text);
char[] chars = new char[text.length()];
int pos = 0;
int n;
String readStr = "";
do {
n = source.read(chars, 0, chars.length - pos);
if (n > 0) {
pos += n;
readStr = readStr + new String(chars, 0, n);
}
if (readStr.endsWith("\r")) {
try {
char c = (char) source.read();
if (c != '\n') source.unread(c);
else readStr += c;
} catch (IOException ioex) {}
}
readStr = adjustTextNL(readStr);
pos = readStr.length();
} while (n > 0 && pos < chars.length);
readStr.getChars(0, readStr.length(), chars, 0);
line += numChars('\n', chars);
//System.out.println("Comparing text of the diff:\n'"+text+"'\nWith the read text:\n'"+readStr+"'\n");
//System.out.println(" EQUALS = "+readStr.equals(text));
return readStr.equals(text);
}
private String parseIntPart(PushbackReader in) throws IOException {
StringBuilder sb=new StringBuilder();
while(true){
int c=in.read();
if(c>='0' && c<='9'){
sb.append((char)c);
}
else {
if(c>=0) in.unread(c);
if(sb.length()==0) return null;
else return sb.toString();
}
}
}
public ReaderStream<ParentMatch> use(Reader reader, int bufSize) {
if(bufSize > 0){
this.bufSize = bufSize;
}
this.reader = new PushbackReader(reader, this.bufSize);
return this;
}
public ReaderStream<ParentMatch> use(PushbackReader reader, int bufSize, ParentMatch parentMatch) {
if(bufSize < 1){
this.reader = new PushbackReader(reader, this.bufSize);
this.parentMatch = parentMatch;
return this;
}
this.bufSize = bufSize;
this.reader = reader;
this.parentMatch = parentMatch;
return this;
}
public ReaderStream<ParentMatch> use(Reader reader, int bufSize, ParentMatch parentMatch) {
if(bufSize > 0){
this.bufSize = bufSize;
}
this.reader = new PushbackReader(reader, this.bufSize);
this.parentMatch = parentMatch;
return this;
}
private static String getNextTag(PushbackReader stream) throws IOException {
String tag = null;
int ch = 0;
while ((ch = stream.read()) != -1) {
if (ch == START_TAG) {
tag = getTagName(stream);
break;
}
}
return tag;
}
@Test
public void streamTest() {
String edn = "{:x 1}{:x 2}{:x 3}";
PushbackReader reader = new PushbackReader(new StringReader(edn));
Stream<StreamingType> stream = deserializeStream(reader, StreamingType.class);
assertEquals(6, stream.mapToInt(StreamingType::x).sum());
}
/** Creates a new instance of CsvRecordInput */
public CsvRecordInput(InputStream in) {
try {
stream = new PushbackReader(new InputStreamReader(in, "UTF-8"));
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}