Lab Exercises
- Exercise 1: Byte stream (20 minutes)
- Exercise 2: Character stream (20 minutes)
- Exercise 3: Buffered stream (20 minutes)
- Exercise 4: Data stream (20 minutes)
- Exercise 5: Object stream (20 minutes)
- Exercise 6: Pipe stream (20 minutes)
- Exercise 7: File handling (20 minutes)
- Exercise 8: Filtered stream (20 minutes)
- Exercise 9: Scanner and Formatter (20 minutes)
- Homework Exercise (for people who are taking Sang Shin’s “Java Programming online course”)
Exercise 1: Byte stream
(1.1) Write an application that uses FileInputStream and FileOutputStream
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N).
- Observe that the New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in FileInputOutputStream as project name.
- For Create Main Class field, type in FileInputOutputStream. (Figure-1.10 below)
- Click Finish.
Figure-1.10: Create a new project
- Observe that FileInputOutputStream project appears and IDE generated FileInputOutputStream.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated FileInputOutputStream.java as shown in Code-1.11 below. Study the code by paying special attention to the bold fonted parts.
import java.io.*;
public class FileInputOutputStream { public static void main(String[] args) throws IOException { File inputFile = new File(“farrago.txt”); FileInputStream in = new FileInputStream(inputFile); while ((c = in.read()) != -1){ System.out.println(“FileInputStream is used to read a file and FileOutPutStream is used for writing.”); in.close(); |
Code-1.11: FileInputOutputStream.java
3. Provide farrago.txt as an input file.
- Right click FileInputOutputStream project and select New->Other.
- Observe the New File dialog box appears.
- Choose Other under Categories and Empty File under File Types. (Figure-1.12 below)
- Click Next.
Figure-1.12: Create Empty File
- Observe that the New Empty File dialog box appears.
- For the File Name field, type in farrago.txt.
- Click Finsh.
- Observe that the empty farrago.txt appears in the editor window.
- Cut and paste the contents from the InputFile-1.14 below to the empty file.
So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a great she-bear, coming up the street, pops its head into the shop. ‘What! no soap?’ So he died, and she very imprudently married the barber; and there were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum himself, with the little round button at top, and they all fell to playing the game of catch as catch can, till the gun powder ran out at the heels of their boots. Samuel Foote 1720-1777 |
InputFile-1.14: farrago.txt
4. Build and run the project
- Right click FileInputOutputStream project and select Run Project.
- Observe the result in the Output window. (Figure-1.15 below)
… 55 55 55 10 FileInputStream is used to read a file and FileOutPutStream is used for writing. |
Figure-1.15: Result of running FileInputOutputStream application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/FileInputOutputStream. You can just open it and run it.
5. For your own exercise, modify FileInputOutputStream.java as following. Build and run the application.
- Read your own file, myowninputfile.txt, and write it to another file, myownoutputfile.txt.
Summary
Exercise 2: Character Stream
(2.1) Write an application that uses FileReader and FileWriter
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in FileReaderWriter as project name.
- For Create Main Class field, type in FileReaderWriter.
- Click Finish.
- Observe that FileReaderWriter project appears and IDE generated FileReaderWriter.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated FileReaderWriter.java as shown in Code-2.11 below. Study the code by paying special attention to the bold fonted parts.
import java.io.*;
public class FileReaderWriter { public static void main(String[] args) throws IOException { File inputFile = new File(“farrago.txt”); FileReader in = new FileReader(inputFile); while ((c = in.read()) != -1){ System.out.println(“FileReader is used to read a file and FileWriter is used for writing.”); in.close(); |
Code-2.11: FileReaderWriter.java
3. Provide farrago.txt as an input file.
So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a great she-bear, coming up the street, pops its head into the shop. ‘What! no soap?’ So he died, and she very imprudently married the barber; and there were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum himself, with the little round button at top, and they all fell to playing the game of catch as catch can, till the gun powder ran out at the heels of their boots. Samuel Foote 1720-1777 |
File-2.12: farrago.txt
4. Build and run the project
- Right click FileReaderWriter project and select Run Project.
- Observe the result in the Output window. (Figure-2.13 below)
… 55 55 55 10 FileReader is used to read a file and FileWriter is used for writing. |
Figure-2.13: Result of running FileReaderWriter application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/FileReaderWriter. You can just open it and run it.
5. For your own exercise, modify FileReaderWriter.java as following. Build and run the application. (This is not a homework. No submission is required.)
- Read your own file, myowninputfile.txt, and write it to another file, myownoutputfile.txt.
Summary
In this exercise, you learned how to use FileReaderclass which is Reader type and FileWriter class which is Writer type to read from and write to a file.
Exercise 3: Buffered Stream
In this exercise, you will learn how to use BufferedReader and BufferedWriter classes for performing buffered I/O operations.
(3.1) Write an application that uses BufferedReader and BufferedWriter classes
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in BufferedReaderWriter as project name.
- For Create Main Class field, type in BufferedReaderWriter.
- Click Finish.
- Observe that BufferedReaderWriter project appears and IDE generated BufferedReaderWriter.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated BufferedReaderWriter.java as shown in Code-3.11 below. Study the code by paying special attention to the bold fonted parts.
public class BufferedReaderWriter {
public static void main(String args[]) { String a0, a1, a2; if (args.length != 3){ SimpleEncryption se = new SimpleEncryption(); /* print content of encrypted file */ } |
Code-3.11: BufferedReaderWriter.java
- Observe that there are some compile errors. This is expected.
3. Write SimpleEncryption.java as shown in Code-3.12 below. Study the code by paying special attention to the bold fonted parts.
- Modify the code as shown below.
import java.io.*;
class SimpleEncryption { void encrypt(String source, String dest, int shiftSize) { BufferedReader reader; try { } void viewFileContent(String filename) { BufferedReader reader; } |
Code-3.12: SimpleEncryption.java
4. Write words.txt. (File-3.13 below)
anatomy animation applet application argument bolts class communicate string threads tools user |
File-3.13: words.txt
5. Provide command line arguments.
- Right click BufferedReaderWriter project and select Properties.
- Observe Project Properties dialog box appears.
- Select Run and for the Arguments field, type in words.txt wordsout.txt 3. (Figure-3.14 below)
Figure-3.14: Provide command line arguments
6. Build and run the project
- Right click BufferedReaderWriter project and select Run Project.
- Observe the result in the Output window. (Figure-3.15 below)
Displaying encrypted words from words.txt… dqdwrp| dqlpdwlrq dssohw dssolfdwlrq dujxphqw erowv fodvv frppxqlfdwh vwulqj wkuhdgv wrrov xvhu |
Figure-3.15: Result of running BufferedReaderWriter application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/BufferedReaderWriter. You can just open it and run it.
Summary
Exercise 4: Data Stream
(4.1) DataInputStream and DataOutputStream
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in DataInputOutputStream as project name.
- For Create Main Class field, type in DataInputOutputStream.
- Click Finish.
- Observe that DataInputOutputStream project appears and IDE generated DataInputOutputStream.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated DataInputOutputStream.java as shown in Code-4.11 below. Study the code especially the code fragments that are in bold-fonted font.
import java.io.*;
public class DataInputOutputStream { public static void main(String[] args) throws IOException { // write the data out double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; for (int i = 0; i < prices.length; i ++) { // read it in again double price; String lineSepString = System.getProperty(“line.separator”); try { |
Code-4.11: DataInputOutputStream.java
5. Build and run the project
- Right click DataInputOutputStream project and select Run Project.
- Observe the result in the Output window. (Figure-4.14 below)
You’ve ordered 12 units of Java T-shirt at $19.99 You’ve ordered 8 units of Java Mug at $9.99 You’ve ordered 13 units of Duke Juggling Dolls at $15.99 You’ve ordered 29 units of Java Pin at $3.99 You’ve ordered 50 units of Java Key Chain at $4.99 For a TOTAL of: $892.8800000000001 |
Figure-4.14: Result of running DataInputOutputStream application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/DataInputOutputStream. You can just open it and run it.
(4.2) DataInput and DataOutput
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in CustomDataInputOutput as project name.
- For Create Main Class field, type in CustomDataInputOutput.
- Click Finish.
- Observe that CustomDataInputOutput project appears and IDE generated CustomDataInputOutput.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated CustomDataInputOutput.java as shown in Code-4.21 below. Study the code especially the code fragments that are in bold-fonted font.
import java.io.*;
public class CustomDataInputOutput { Adler32 inChecker = new Adler32(); try { boolean EOF = false; while (!EOF) { System.out.println(“Input stream check sum: ” + |
Code-4.21: CustomDataInputOutput.java
3. Write CheckedDataInput.java. (Code-4.22 below)
import java.io.*;
public class CheckedDataInput { private Checksum cksum; public CheckedDataInput(DataInput in, Checksum cksum) { public byte readByte() throws IOException { public void readFully(byte[] b) throws IOException { public void readFully(byte[] b, int off, int len) throws IOException { public Checksum getChecksum() { |
Code-4.22: CheckedDataInput.java
4. Write CheckedDataOutput.java. (Code-4.23 below)
import java.io.*;
public class CheckedDataOutput { private Checksum cksum; public CheckedDataOutput(DataOutput out, Checksum cksum) { public void write(int b) throws IOException { public void write(byte[] b) throws IOException { public void write(byte[] b, int off, int len) throws IOException { public Checksum getChecksum() { |
Code-4.23: CheckedDataOutput.java
5. Write Checksum.java. (Code-4.24 below)
public interface Checksum { /** * Updates the current checksum with the specified byte. */ public void update(int b); /** /** /** |
Code-4.24: Checksum.java
6. Write Adler32.java. (Code-4.25 below)
public class Adler32 implements Checksum { private int value = 1; /* /** /** while (len > 0) { /** /** |
Code-4.25: Adler32.java
7. Provide farrago.txt as an input file.
So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a great she-bear, coming up the street, pops its head into the shop. ‘What! no soap?’ So he died, and she very imprudently married the barber; and there were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum himself, with the little round button at top, and they all fell to playing the game of catch as catch can, till the gun powder ran out at the heels of their boots. Samuel Foote 1720-1777 |
File-2.12: farrago.txt
8. Build and run the project
- Right click CustomDataInputOutput project and select Run Project.
- Observe the result in the Output window. (Figure-4.14 below)
Input stream check sum: 736868089 Output stream check sum: 736868089 |
Figure-4.14: Result
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/CustomDataInputOutput. You can just open it and run it.
Summary
Exercise 5: Object Stream
(5.1) Write an application that uses ObjectInputStream and ObjectOutputStream classes
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in ObjectInputOutputStream as project name.
- For Create Main Class field, type in ObjectInputOutputStream.
- Click Finish.
- Observe that ObjectInputOutputStream project appears and IDE generated ObjectInputOutputStream.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated ObjectInputOutputStream.java as shown in Code-5.11 below.
import java.io.*;
public class ObjectInputOutputStream { public static void main(String[] args) { Card3 card = new Card3(12, Card3.SPADES); try { try { System.out.println(“Card read is: ” + card); |
Code-5.11: ObjectInputOutputStream.java
3. Write Card3.java as shown in Code-5.12 below. Study the code by paying special attention to the bold fonted parts.
import java.io.Serializable;
public class Card3 implements Serializable { public final static int UNASSIGNED = -1; public final static int DIAMONDS = 1; public final static int ACE = 1; public Card3(int number, int suit) { if (isValidSuit(suit)) { public int getSuit() { public int getNumber() { public static boolean isValidNumber(int number) { public boolean equals(Object obj) { public static String numberToString(int number) { public static String suitToString(int suit) { |
Code-5.12: Card3.java
4. Build and run the project
- Right click ObjectInputOutputStream project and select Run Project.
- Observe the result in the Output window. (Figure-5.15 below)
Card to write is: Queen of Spades Card read is: Queen of Spades |
Figure-5.15: Result
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/ObjectInputOutputStream. You can just open it and run it.
Summary
Exercise 6: Piped Stream
(6.1) Pipe stream
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in PipedReaderWriter as project name.
- For Create Main Class field, type in PipedReaderWriter.
- Click Finish.
- Observe that PipedReaderWriter project appears and IDE generated PipedReaderWriter.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated PipedReaderWriter.java as shown in Code-6.11 below. Study the code by paying special attention to the bold fonted parts.
import java.io.*;
public class PipedReaderWriter { public static Reader reverse(Reader source) throws IOException { BufferedReader in = new BufferedReader(source); PipedWriter pipeOut = new PipedWriter(); new ReverseThread(out, in).start(); return pipeIn; public static Reader sort(Reader source) throws IOException { BufferedReader in = new BufferedReader(source); PipedWriter pipeOut = new PipedWriter(); new SortThread(out, in).start(); return pipeIn; public static void main(String[] args) throws IOException { FileReader words = new FileReader(“words.txt”); // do the reversing and sorting // write new list to standard out while ((input = in.readLine()) != null) } |
Code-6.11: PipedReaderWriter.java
3. Write ReverseThread.java.
import java.io.*;
public class ReverseThread extends Thread { public ReverseThread(PrintWriter out, BufferedReader in) { public void run() { private String reverseIt(String source) { for (i = (len – 1); i >= 0; i–) |
Code-6.12: ReserveThread.java
4. Write SortThread.java.
import java.io.*;
public class SortThread extends Thread { public SortThread(PrintWriter out, BufferedReader in) { public void run() { if (out != null && in != null) { while ((listOfWords[numwords] = in.readLine()) != null) private static void quicksort(String[] a, int lo0, int hi0) { if (lo >= hi) String mid = a[(lo + hi) / 2]; |
Code-6.13: SortThread.java
5. Create words.txt file as a input file.
anatomy animation applet application argument bolts class communicate user |
File-6.14: words.txt
6. Build and run the project
- Right click PipedReaderWriter project and select Run Project.
- Observe the result in the Output window. (Figure-6.15 below)
communicate application animation user class bolts applet argument anatomy |
Figure-6.15: Result of running UnPipedReaderWriter application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/PipedReaderWriter. You can just open it and run it.
Summary
Exercise 7: File and Directory Handling
(7.1) File handling
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in FileInfo as project name.
- For Create Main Class field, type in FileInfo.
- Click Finish.
- Observe that FileInfo project appears and IDE generated FileInfo.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated FileInfo.java as shown in Code-6.11 below. Study the code by paying special attention to the bold fonted parts.
import java.io.File; import java.io.IOException; public class FileInfo { public static void main(String[] args) { // The first command line argument needs to be provided } // Check if the file exists using exists() method if (fn.canRead()) { System.out.println(fileName + ” is ” + fn.length() + ” bytes long.”); if (fn.canWrite()) { |
Code-7.11: FileInfo.java
3. Provide command line arguments.
- Right click FileInfo project and select Properties.
- Observe Project Properties dialog box appears.
- Select Run and for the Arguments field, type in dummyname. (Figure-3.13 below)
4. Build and run the project
- Right click FileInfo project and select Run Project.
- Observe the result in the Output window. (Figure-6.12 below)
Name: dummyname dummyname does exist. dummyname is readable. dummyname is 0 bytes long. dummyname is last modifed at Sat Feb 24 15:36:28 EST 2007 dummyname is writable. |
Figure-7.12: Result of running UnFileInfo application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/FileInfo. You can just open it and run it.
(7.2) Directory handling
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in DirectoryInfo as project name.
- For Create Main Class field, type in DirectoryInfo.
- Click Finish.
- Observe that DirectoryInfo project appears and IDE generated DirectoryInfo.java is displayed in the source editor window of NetBeans IDE.
import java.io.File;
public class DirectoryInfo { public static void main(String[] args) { // Create a directory // Create sub directories under the temp directory // Check if it is a file or directory using isFile() method if (fn.isDirectory()) { // Delete a directory } |
Code-7.21: DirectoryInfo.java
- Right click DirectoryInfo project and select Run Project.
- Observe the result in the Output window. (Figure-7.22 below)
Creating temp directory… temp is a directory. The content of this directory: subdir1 subdir2 temp exists Deleting temp directory… |
Figure-7.22: Result
(7.3) Random access file handling
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in RandomAccessFileHandling as project name.
- For Create Main Class field, type in RandomAccessFileHandling.
- Click Finish.
- Observe that RandomAccessFileHandling project appears and IDE generated RandomAccessFileHandling.java is displayed in the source editor window of NetBeans IDE.
import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileHandling { public static void main(String[] args) { // change the 3rd integer from 88 to 99 |
Code-7.31: RandomAccessFileHandling.java
- Right click RandomAccessFileHandling project and select Run Project.
- Observe the result in the Output window. (Figure-6.22 below)
10 43 99 455 |
Figure-7.32: Result
Summary
Exercise 8: Filter Streams
(8.1) Create custom stream class that extends Filter streams
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in FilterInputOutputStream as project name.
- For Create Main Class field, type in FilterInputOutputStream.
- Click Finish.
- Observe that FilterInputOutputStream project appears and IDE generated FilterInputOutputStream.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated FilterInputOutputStream.java as shown in Code-8.11 below. Study the code by paying special attention to the bold fonted parts.
import java.io.*;
public class FilterInputOutputStream { public static void main(String[] args) throws IOException { Adler32 inChecker = new Adler32(); try { int c; while ((c = in.read()) != -1) System.out.println(“Input stream check sum: ” + in.close(); |
Code-8.11: FilterInputOutputStream.java
3. Write CheckedInputStream.java. (Code-8.12 below)
import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; // Custom InputStream private Checksum cksum; public CheckedInputStream(InputStream in, Checksum cksum) { public int read() throws IOException { public int read(byte[] b) throws IOException { public int read(byte[] b, int off, int len) throws IOException { public Checksum getChecksum() { |
Code-8.12: CheckedInputStream.java
4. Write CheckedOutputStream.java. (Code-8.13 below)
import java.io.*;
// Custom OutputStream private Checksum cksum; public CheckedOutputStream(OutputStream out, Checksum cksum) { public void write(int b) throws IOException { public void write(byte[] b) throws IOException { public void write(byte[] b, int off, int len) throws IOException { public Checksum getChecksum() { |
Code-8.13: CheckedOutputStream.java
5. Write Checksum.java. (Figure-8.14 below)
public interface Checksum { /** * Updates the current checksum with the specified byte. */ public void update(int b); /** /** /** |
Code-8.14: Checksum.java
6. Write Adler32.java. (Code-8.15 below)
public class Adler32 implements Checksum {
private int value = 1; /* /** /** while (len > 0) { /** /** |
Code-8.15: Checksum.java
7. Provide farrago.txt as an input file.
So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a great she-bear, coming up the street, pops its head into the shop. ‘What! no soap?’ So he died, and she very imprudently married the barber; and there were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum himself, with the little round button at top, and they all fell to playing the game of catch as catch can, till the gun powder ran out at the heels of their boots. Samuel Foote 1720-1777 |
File-2.12: farrago.txt
8. Build and run the project
- Right click FilterInputOutputStream project and select Run Project.
- Observe the result in the Output window. (Figure-8.16 below)
Input stream check sum: 736868089 Output stream check sum: 736868089 |
Figure-8.16: Result
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/FilterInputOutputStream. You can just open it and run it.
Summary
Exercise 9: Scanner and Formatter
breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. Scanner class is introduced from Java SE 5.
(9.1) Scanner class
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in ScannerClass as project name.
- For Create Main Class field, type in ScannerClass.
- Click Finish.
- Observe that ScannerClass project appears and IDE generated ScannerClass.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated ScannerClass.java as shown in Code-6.11 below. Study the code by paying special attention to the bold fonted parts.
import java.io.*; import java.util.*; public class ScannerClass { public static void main(String[] args) throws IOException { Scanner s = double sum = 0; while (s.hasNext()) { System.out.println(“Sum of all numbers = ” + sum); |
Code-9.11: ScannerClass.java
3. Provide usnumbers.txt as input data file.
8.5 32,767 3.14159 1,000,000.1 |
File-9.12: usnumbers.txt
4. Build and run the project
- Right click ScannerClass project and select Run Project.
- Observe the result in the Output window. (Figure-6.12 below)
Sum of all numbers = 1032778.74159 |
Figure-6.12: Result
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javaiostream/samples/ScannerClass. You can just open it and run it.
(9.2) Format class
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in FormatClass as project name.
- For Create Main Class field, type in FormatClass.
- Click Finish.
- Observe that FormatClass project appears and IDE generated FormatClass.java is displayed in the source editor window of NetBeans IDE.
public class FormatClass { public static void main(String[] args) { System.out.format(“%f, %1$+020.10f %n”, Math.PI); } } |
Code-6.21: FormatClass.java
- Right click FormatClass project and select Run Project.
- Observe the result in the Output window. (Figure-6.22 below)
3.141593, +00000003.1415926536 |
Figure-6.22: Result
Summary
Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)
- Write ChangeToUpperCaseInputStream class, which extends FilterInputStream.
- Write ChangeToUpperCaseOutputStream class, which extends FilterOutputStream.
- Use either ChangeToUpperCaseInputStream class or ChangeToUpperCaseOutputStream class to convert the characters read to upper case.
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javaiostream.
- Zip file of the the MyIOStreamProject NetBeans project. (Someone else should be able to open and run it as a NetBeans project.) You can use your favorite zip utility or you can use “jar” utility that comes with JDK as following.
- cd <parent directory that contains MyIOStreamProject directory> (assuming you named your project as MyIOStreamProject)
- jar cvf MyIOStreamProject.zip MyIOStreamProject (MyIOStreamProject should contain nbproject directory)
- Captured output screen – name it as JavaIntro-javaiostream.gif or JavaIntro-javaiostream.jpg (or JavaIntro-javaiostream.<whatver graphics format>)
- Any screen capture that shows that your program is working is good enough. No cosmetic polishment is required.
- If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project.