Sunday, March 20, 2011

How to Use BufferedInputStream in Java


1. Open a new Java class file. If you are using a Java Integrated Development Environment (IDE) like Netbeans, then you should be able to do this by clicking \"File,\" and \"New Class.\" Otherwise, just open a copy of your favorite text editor, such as Notepad, and click \"File,\" then \"Save as.\" Name the file \"BufferedExample.java.\" Paste the following code into your new file to import the BufferedInputStream from the Java IO library: <br /><br />import java.io.BufferedInputStream;
2. Paste the following to create an outline for your Java program. If you are using an IDE like Netbeans, this may have been done automatically for you. If so, skip to <br />Step 3.<br /><br />public class BufferedExample {<br /><br /> public static void main(String[] args) {<br /> <br /> }<br /><br />}
3. Paste the following code inside the \"public static void main\" method of your class skeleton. <br /><br /> BufferedInputStream in = new BufferedInputStream(System.in)<br />GO<br /> // Mark this spot in the stream to come back to later. <br /> // The 1024 specifies that the buffer will hold 1024 bytes of data.<br /> // Should more data than this be read, the bookmark will become invalid.<br /> in.mark(1024)<br />GO<br /> try {<br /> int x = in.read()<br />GO<br /> // Print out the ASCII keycode for the character typed. For example, 'a' is 97.<br /> System.out.println(x)<br />GO<br /> // Return to the spot marked a few lines ago.<br /> in.reset()<br />GO<br /> // This will read and print the same value again.<br /> int y = in.read()<br />GO<br /> System.out.println(y)<br />GO<br /><br /> } catch (Exception e) {<br /> System.out.println(\"Error\")<br />GO<br /> }<br /><br />This code creates a new BufferedInputStream from the \"System.in\" value, which is set to the user's keyboard by default, allowing her to type in data for the program. It immediately marks the beginning of the stream. It then reads one character from the keyboard and stores it as an integer of its American Standard for Code Information Interchange (ASCII) keycode. BufferedInputStream always returns a collection of integers between 0 and 255, or bytes. How to interpret these bytes is left to you as a programmer. After it has read and printed out what it received, it returns to its bookmark, reads, and prints again.