Continuing on binary input and output in java
The term " block " means that the method and the program will be suspended. The program will resume only when the method returns. Two variations of read methods are implemented in the InputStream for reading a block of bytes into a byte-array. It returns the number of bytes read, or -1 if "end-of-stream" encounters. Similar to the input counterpart, the abstract superclass OutputStream declares an abstract method write to write a data-byte to the output sink.
The least-significant byte of the int argument is written out; the upper 3 bytes are discarded. Similar to the read , two variations of the write method to write a block of bytes from a byte-array are implemented:. Both the InputStream and the OutputStream provides a close method to close the stream, which performs the necessary clean-up operations to free up the system resources. This could prevent serious resource leaks.
Unfortunately, the close method also throws a IOException , and needs to be enclosed in a nested try-catch statement, as follows. This makes the codes somehow ugly. This produces much neater codes. In addition, the OutputStream provides a flush method to flush the remaining bytes from the output buffer. InputStream and OutputStream are abstract classes that cannot be instantiated. You need to choose an appropriate concrete subclass to establish a connection to a physical device. For example, we can layer a BufferedInputStream to a FileInputStream for buffered input, and stack a DataInputStream in front for formatted data input using primitives such as int , double , as illustrated in the following diagrams.
This is grossly inefficient, as each call is handled by the underlying operating system which may trigger a disk access, or other expensive operations. To chain the streams together, simply pass an instance of one stream into the constructor of another stream.
This example copies a file by reading a byte from the input file and writing it to the output file. The method close is programmed inside the finally clause. It is guaranteed to be run after try or catch. However, method close also throws an IOException , and therefore must be enclosed inside a nested try-catch block, which makes the codes a little ugly. The output shows that it took about 4 seconds to copy a KB file.
As mentioned, JDK 1. For example, the above example can be re-written in a much neater manner as follow:. This program took only 3 millisecond - a more than times speed-up compared with the previous example.
However, there is a trade-off between speed-up the the memory usage. For file copying, a large buffer is certainly recommended. But for reading just a few bytes from a file, large buffer simply wastes the memory.
I re-write the program using JDK 1. The JRE decides on the buffer size. The program took 62 milliseconds, about 60 times speed-up compared with example 1, but slower than the programmer-managed buffer. To use DataInputStream for formatted input, you can chain up the input streams as follows:. DataInputStream implements DataInput interface, which provides methods to read formatted primitive data and String , such as:.
DataOutputStream implements DataOutput interface, which provides methods to write formatted primitive data and String. The following program writes some primitives to a disk file. It then reads the raw bytes to check how the primitives were stored. Finally, it reads the data as primitives. The data stored in the disk are exactly in the same form as in the Java program internally e. The byte-order is big-endian big byte first, or most significant byte in lowest address.
If this character is to be written to a file uses UTF-8, the character stream needs to translate " 60 A8 " to " E6 82 A8 ". The reserve takes place in a reading operation. This is because some charsets use fixed-length of 8-bit e. When a character stream is used to read an 8-bit ASCII file, an 8-bit data is read from the file and put into the bit char location of the Java program.
The abstract superclass Reader operates on char. It declares an abstract method read to read one character from the input source. There are also two variations of read to read a block of characters into char -array. The abstract superclass Writer declares an abstract method write , which writes a character to the output sink. The lower 2 bytes of the int argument is written out; while the upper 2 bytes are discarded.
The default charset is kept in the JVM's system property " file. You can get the default charset via static method java. BufferedReader provides a new method readLine , which reads a line and returns a String without the line delimiter. The main class java. Charset provides static methods for testing whether a particular charset is supported, locating charset instances by name, and listing all the available charsets and the default charset.
The default charset for file encoding is kept in the system property " file. For example, the following command run the program with default charset of UTF The following example encodes some Unicode texts in various encoding scheme, and display the Hex codes of the encoded byte sequences. As mentioned, Java internally stores characters char type in bit UCS-2 character set.
You can list the available charsets via static method java. The commonly-used Charset names supported by Java are:. The following program writes Unicode texts to a disk file using various charsets for file encoding. It then reads the file byte-by-byte via a byte-based input stream to check the encoded characters in the various charsets.
Finally, it reads the file using the character-based reader. Primitives are converted to their string representation for printing. The printf and format were introduced in JDK 1. Instead, it sets an internal flag which can be checked via the checkError method.
A PrintStream can also be created to flush the output automatically. The standard output and error streams System. All characters printed by a PrintStream are converted into bytes using the default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes.
The character-stream PrintWriter is similar to PrintStream , except that it write in characters instead of bytes. The PrintWriter also supports all the convenient printing methods print , println , printf and format. It never throws an IOException and can optionally be created to support automatic flushing.
Data streams DataInputStream and DataOutputStream allow you to read and write primitive data such as int , double and String , rather than individual bytes. Object streams ObjectInputStream and ObjectOutputStream go one step further to allow you to read and write entire objects such as Date , ArrayList or any custom objects.
Object serialization is the process of representing a "particular state of an object" in a serialized bit-stream, so that the bit stream can be written out to an external device such as a disk file or network. The bit-stream can later be re-constructed to recover the state of that object.
Object serialization is necessary to save a state of an object into a disk file for persistence or sent the object across the network for applications such as Web Services, Distributed-object applications, and Remote Method Invocation RMI. In Java, object that requires to be serialized must implement java. Serializable interface is an empty interface or tagged interface with nothing declared. Its purpose is simply to declare that particular object is serializable.
For example, the following code segment writes objects to a disk file. To read and re-construct the object back in a program, use the method readObject , which returns an java. Downcast the Object back to its original type. You can used methods such as readInt , readDouble , writeInt , writeDouble for reading and writing primitive types. When you create a class that might be serialized, the class must implement java. The Serializable interface doesn't declare any methods. Empty interfaces such as Serializable are known as tagging interfaces.
They identify implementing classes as having certain properties, without requiring those classes to actually implement any methods. Most of the core Java classes implement Serializable , such as all the wrapper classes, collection classes, and GUI classes. In fact, the only core Java classes that do not implement Serializable are ones that should not be serialized. Arrays of primitives or serializable objects are themselves serializable. This warning message is triggered because your class such as java.
JFrame implements the java. This interface enables the object to be written out to an output stream serially via method writeObject ; and read back into the program via method readObject. The serialization runtime uses a number called serialVersionUID to ensure that the object read into the program during deserialization is compatible with the class definition, and not belonging to another version. It throws an InvalidClassException otherwise.
The Serializable has a sub-interface called Externalizable , which you could used if you want to customize the way a class is serialized. Since Externalizable extends Serializable , it is also a Serializable and you could invoke readObject and writeObject. When an instance of Externalizable is passed to an ObjectOutputStream , the default serialization procedure is bypassed; instead, the stream calls the instance's writeExternal method. Similarly, when an ObjectInputStream reads a Exteranlizabled instance, it uses readExternal to reconstruct the instance.
For example, you could encrypt sensitive data before the object is serialized. That is, they are either read-only input stream or write-only output stream. Furthermore, they are all sequential-access or serial streams, meant for reading and writing data sequentially. Nonetheless, it is sometimes necessary to read a file record directly as well as modifying existing records or inserting new records.
The class RandomAccessFile provides supports for non-sequential, direct or random access to a disk file. RandomAccessFile is a two-way stream, supporting both input and output operations in the same stream. RandomAccessFile can be treated as a huge byte array. You can use a file pointer of type long , similar to array index, to access individual byte or group of bytes in primitive types such as int and double. The file pointer is located at 0 when the file is opened.
It advances automatically for every read and write operation by the number of bytes processed. In constructing a RandomAccessFile , you can use flags 'r' or 'rw' to indicate whether the file is "read-only" or "read-write" access, e. Read and write records from a RandomAccessFile. A student file consists of student record of name String and id int. Scanner class, which greatly simplifies formatted text input from input source e. Scanner , as the name implied, is a simple text scanner which can parse the input text into primitive types and strings using regular expressions.
It first breaks the text input into tokens using a delimiter pattern, which is by default the white spaces blank, tab and newline. The tokens may then be converted into primitive values of different types using the various nextXxx methods nextInt , nextByte , nextShort , nextLong , nextFloat , nextDouble , nextBoolean , next for String , and nextLine for an input line.
You can also use the hasNextXxx methods to check for the availability of a desired input. The commonly-used constructors are as follows. You can construct a Scanner to parse a byte-based InputStream e. The most common usage of Scanner is to read primitive types and String form the keyboard System. The nextXxx methods throw InputMismatchException if the next token does not match the type to be parsed.
You can easily modify the above program to read the inputs from a text file, instead of keyboard System. You can use hasNext coupled with next to iterate through all the String tokens.
You can also directly iterate through the primitive types via methods hasNextXxx and nextXxx. Xxx includes all primitive types byte , short , int , long , float , double and boolean , BigInteger, and BigNumber. Instead of the default white spaces as the delimiter, you can set the delimiter to a chosen regular expression via these methods:. Read " Regular Expression " for more details.
You can use the following methods to find the next occurrence of the specified pattern using regular expressions:. By default, Scanner uses the default charset to read the character from the input source. You can ask Scanner to read text file which is encoded using a particular charset, by providing the charset name.
PrintWriter for formatted-text printing. To write formatted-text to console System. The "Hello, World" program for animation is to produce a black ball that appears to move around on the canvas, bouncing off the boundary according to the laws of elastic collision. We do so in four steps: Clear the offscreen canvas to white.
Draw a black ball at the new position on the offscreen canvas. Copy the offscreen canvas to the onscreen canvas. To create the illusion of movement, BouncingBall. Our standard draw library supports drawing pictures as well as geometric shapes. Our standard draw library also includes methods so that the user can interact with the window using the mouse. It draws a blue ball, centered on the location of the mouse. When the user holds down the mouse button, the ball changes color from blue to cyan.
It also accounts for a drag force. When the user clicks, the balls disperse randomly. StdAudio is a library that you can use to play and manipulate sound files. It allows you to play, manipulate and synthesize sound. We introduce some some basic concepts behind one of the oldest and most important areas of computer science and scientific computing: Concert A is a sine wave, scaled to oscillate at a frequency of times per second.
The amplitude y -value corresponds to the volume. A simple mathematical formula characterizes the other notes on the chromatic scale. They are divided equally on a logarithmic base 2 scale: When you double or halve the frequency, you move up or down an octave on the scale. For example hertz is one octave above concert A and hertz is two octaves below concert A.
For digital sound, we represent a curve by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. We sample sufficiently often that we have an accurate representation of the curve—a widely used sampling rate is 44, samples per second. It is that simple: For example, the following code fragment plays concert A for 10 seconds. It takes notes from standard input, indexed on the chromatic scale from concert A, and plays them on standard audio.
Exercises Write a program MaxMin. Write a program Stats. Write a program LongestRun. For example, if the input is 1 2 2 1 5 1 1 7 7 7 7 1 1 , then your program should print Longest run: Write a program WordCount. For the purpose of this exercise, a word is a sequence of non-whitespace characters that is surrounded by whitespace.
Write a program Closest. For efficiency, do not use Math. Given the positions and masses of a sequence of objects, write a program to compute their center-of-mass or centroid. The centroid is the average position of the n objects, weighted by mass. If the positions and masses are given by x i , y i , m i , then the centroid x , y , m is given by: Write a program Checkerboard.
Color the lower-left square red. Write a program Rose. Write a program Banner. Add a second command-line argument to control the speed. Write a program Circles. Your program should take four command-line arguments: Write a program Spirograph. A spirograph technically, an epicycloid is a curve formed by rolling a circle of radius r around a larger fixed circle or radius R.
For a dramatic 3d effect, draw a circular image, e. Write a program Clock. Use the method StdDraw. Write a program Oscilloscope. These patterns are named after the French physicist, Jules A.
Lissajous, who studied the patterns that arise when two mutually perpendicular periodic disturbances occur simultaneously. Assume that the inputs are sinusoidal, so tha the following parametric equations describe the curve: The other has parameters 1, 1, 5, 3, 30, 45 Web Exercises Word and line count.
Write a program Rainfall. Write a program Duplicates. Write a program RunLengthEncoder. Write a program RunLengthDecoder. Print the whole file if it consists of Print a random word.
Read a list of N words from standard input, where N is unknown ahead of time, and print out one of the N words uniformly at random. Do not store the word list. Instead, use Knuth's method: Print out the word that survives after reading in all of the data. Julius Caesar sent secret messages to Cicero using a scheme that is now known as a Caesar cipher.
Each letter is replaced by the letter k positions ahead of it in the alphabet and you wrap around if needed. Write a program Caesar. If a letter is not an uppercase letter, simply print it back out. How would you decode a message encrypted using a Caesar cipher? A Boolean matrix has the parity property when each row and each column has an even sum.
This is a simple type of error-correcting code because if one bit is corrupted in transmission bit is flipped from 0 to 1 or from 1 to 0 it can be detected and repaired. Here's a 4 x 4 input file which has the parity property: Use as little internal storage as possible. You are interviewing N candidates for the sole position of American Idol.
Every minute you get to see a new candidate, and you have one minute to decide whether or not to declare that person the American Idol. You may not change your mind once you finish interviewing the candidate. Suppose that you can immediately rate each candidate with a single real number between 0 and 1, but of course, you don't know the rating of the candidates not yet seen. Write a program Diamonds. Create a function to plot an N-gon, centered on x, y of size length s.
Use the function to draws nested polygons like the picture below. Write a program BulgingSquares. Suppose that N mice that start on the vertices of a regular polygon with N sides, and they each head toward the nearest other mouse in counterclockwise direction until they all meet. Write a program to draw the logarithmic spiral paths that they trace out by drawing nested N-gons, rotated and shrunk as in this animation. Write a program to draw a spiral like the one below.
Write a program Globe. Write a program RandomText. Write a program RandomWalk. Start at the center of a 2N-by-2N grid. The current location is displayed in blue; the trail in white. You are seated at a rotating square table like a lazy Susan , and there are four coins placed in the four corners of the table.
Your goal is to flip the coins so that they are either all heads or all tails, at which point a bell rings to notify you that you are done. You may select any two of them, determine their orientation, and optionally flip either or both of them over. To make things challenging, you are blindfolded, and the table is spun after each time you select two coins. Write a program RotatingTable. Then, it prompts the user to select two positions , and identifies the orientation of each coin.
Next, the user can specify which, if any of the two coins to flip. The process repeats until the user solves the puzzle. Write another program RotatingTableSolver. One effective strategy is to choose two coins at random and flip them to heads. However, if you get really unlucky, this could take an arbitrary number of steps. Hex is a two-player board game popularized by John Nash while a graduate student at Princeton University, and later commercialized by Parker Brothers.
It is played on a hexagonal grid in the shape of an by diamond. Write a program Hex. Projectile motion with drag. Write a program BallisticMotion. Account for gravitational and drag forces. Assume that the drag force is proportional to the square of the velocity. Using Newton's equations of motions and the Euler-Cromer method, update the position, velocity, and acceleration according to the following equations: Write a program Heart.
Draw a diamond, then draw two circles to the upper left and upper right sides. Write a program that draws a square and changes its color each second. Repeat the previous exercise, but animate the Lissajous patterns as in this applet.
Bresenham's line drawing algorithm. To plot a line segment from x1, y1 to x2, y2 on a monitor, say by, you need to make a discrete approximation to the continuous line and determine exactly which pixels to turn on. Write a program Madness. You should get the following complex picture. Experiment by changing the parameters and produce original pictures. Write a program Butterfly.
You should get an image like the following butterfly-like figure. The first line contains an integer N that specifies the number of students in the database.
Each of the next N lines consists of four pieces of information, separated by whitespace: Then, the program prints out a list of students in section 4 and 5. In the October 7, California state runoff election for governor, there were official candidates. To avoid the natural prejudice against candidates whose names appear at the end of the alphabet Jon W.
Zellhoefer , California election officials sought to order the candidates in random order. Write a program program Shuffle. California decided to randomize the alphabet instead of shuffling the candidates. Using this strategy, not all N! For example, two candidates with very similar last names will always end up next to each other. Write a program Reverse. This problem investigates two methods for forecasting in time series analysis. Moving average or exponential smoothing.
Create any of these polar plots. Consider the following program. Shuffle a deck of cards, and deal one to the player.
Prompt the player to guess whether the next card is higher or lower than the current card. Repeat until player guesses it wrong. Write a program CollidingBalls. Assume all the balls have the same mass. Elastic collisions with obstacles. Each ball should have its own mass.