1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
/* Java PushbackInputStream Example This example shows how to use Java PushbackInputStream class provided in java.io package. */ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PushbackInputStream; public class JavaPushbackInputStreamExamples { public static void main(String[] args) { //example expression you want to evaluate in your program String strExpression = "a = a++ + b;"; /* * Here, while, evaluating the expression, You need to know * whether it is ++ operator or + plus operator. Basically, * you need to read ahead or peek whether another + follows * immediately after one + sign. */ //get bytes from the expression string byte bytes[] = strExpression.getBytes(); //create stream from expression bytes ByteArrayInputStream bis = new ByteArrayInputStream(bytes); /* * PushbackInputStream provides below given two constructors. * * 1) PushbackInputStream(InputStream is) * creates PushbackInputStream from provided InputStream object * * 2)PushbackInputStream(InputStream is, int size) * Creates PushbackInputStream from specified InputStream object * with pushback buffer of specified size. */ //create PushbackInputStream from ByteArrayInputStream PushbackInputStream pis = new PushbackInputStream(bis); int ch; try { while( (ch = pis.read())!= -1) { //we encountered first + operator if(ch == '+') { //peek to see if another + follows if( (ch = pis.read()) == '+') { System.out.print("Plus Plus"); } else { //push back one position as we did not get another + pis.unread(ch); System.out.print("+"); } } else { //print the character System.out.print((char)ch); } } } catch(IOException ioe) { System.out.println("Exception while reading" + ioe); } } } /* Output of this program would be, a = aPlus Plus + b; */ |
Add Comment