Blakes 21 Days Chapter 15 Document


Day 15, Working with Input and Output

WEEK III - Java Programming
Chapter Title Page
15 Working with Input and Output 419
16 Using Inner Classes and Closures 449
17 Communicating Across the Internet 469
18 Accessing Databases with JDBC 4.2 and Derby 503
19 Reading and Writing RSS Feeds 525
20 XML Web Services 549
21 Writing Android Apps with Java 569

Introduction to Streams

Using a Stream

Filtering a Stream

Handling Exceptions

Byte Streams

File Streams

File Input Streams

First Program

Listing 15.1

The Explanation

Figure 15.1 - Reading byte data from a file. - goes here

440

File Output Streams

Second Program

Listing 15.2

The Explanation

Figure 15.2 - The pic.gif file (enlarged). - goes here

442

Filtering a Stream

Byte Filters

Buffered Streams

Third Program

package com.java21days;

import java.io.*;

public class BufferDemo {
    public static void main(String[] arguments) {
        int start = 0;
        int finish = 255;
        if (arguments.length > 1) {
            start = Integer.parseInt(arguments[0]);
            finish = Integer.parseInt(arguments[1]);
        } else if (arguments.length > 0) {
            start = Integer.parseInt(arguments[0]);
        }
        ArgStream as = new ArgStream(start, finish);
        System.out.println("\nWriting: ");
        boolean success = as.writeStream();
        System.out.println("\nReading: ");
        boolean readSuccess = as.readStream();
    }
}

class ArgStream {
    int start = 0;
    int finish = 255;

    ArgStream(int st, int fin) {
        start = st;
        finish = fin;
    }

    boolean writeStream() {
        try (FileOutputStream file = new
                FileOutputStream("numbers.dat");
            BufferedOutputStream buff = new
                BufferedOutputStream(file)) {

            for (int out = start; out <= finish; out++) {
                buff.write(out);
                System.out.print(" " + out);
            }
            buff.close();
            return true;
        } catch (IOException e) {
            System.out.println("Exception: " + e.getMessage());
            return false;
        }
    }

    boolean readStream() {
        try (FileInputStream file = new
                FileInputStream("numbers.dat");
            BufferedInputStream buff = new
                BufferedInputStream(file)) {

            int in;
            do {
                in = buff.read();
                if (in != -1) {
                    System.out.print(" " + in);
                }
            } while (in != -1);
            System.out.println();
            buff.close();
            return true;
        } catch (IOException e) {
            System.out.println("Exception: " + e.getMessage());
            return false;
        }
    }
}

The Explanation

Figure 15.3 - Reading and writing buffered streams. - goes here

444

Console Input Streams

Fourth Program

Listing 15.4

The Explanation

Figure 15.4 - Reading keyboard input from the console window. - goes here

448

Data Streams

Fifth Program

Listing 15.5 The Full Text of PrimeWriter.java

Sixth Program - Listing 15.6 The Full Text of PrimeReader.java

The Explanations

Figure 15.5 - Reading prime numbers written to a file as integers. - goes here.

450

Character Streams

Reading Text Files

Seventh Program - Listing 15.7 The Full Text of SourceReader.java

The Explanation

Writing Text Files

Files and Paths

Eigth Program - Listing 15.8 The Full Text of AllCapsDemo.java

package com.java21days;

import java.io.*;
import java.nio.file.*;

public class AllCapsDemo {
    public static void main(String[] arguments) {
        if (arguments.length < 1) {
            System.out.println("You must specify a filename");
            System.exit(-1);
        }
        AllCaps cap = new AllCaps(arguments[0]);
        cap.convert();
    }
}

class AllCaps {
    String sourceName;

    AllCaps(String sourceArg) {
        sourceName = sourceArg;
    }

    void convert() {
        try {
            // Create file objects
            FileSystem fs = FileSystems.getDefault();
            Path source = fs.getPath(sourceName);
            Path temp = fs.getPath("tmp_" + sourceName);

            // Create input stream
            FileReader fr = new FileReader(source.toFile());
            BufferedReader in = new BufferedReader(fr);

            // Create output stream
            FileWriter fw = new FileWriter(temp.toFile());
            BufferedWriter out = new
                BufferedWriter(fw);

            boolean eof = false;
            int inChar;
            do {
                inChar = in.read();
                if (inChar != -1) {
                    char outChar = Character.toUpperCase(
                        (char) inChar);
                    out.write(outChar);
                } else
                    eof = true;
            } while (!eof);
            in.close();
            out.close();

            Files.delete(source);
            Files.move(temp, source);
        } catch (IOException|SecurityException se) {
            System.out.println("Error -- " + se.toString());
        }
    }
}

The Explanation



Summary

Q & A

Quiz - Questions

  1. What happens when you create a FileOutputStream using a reference to an existing file ?
    1. An exception is thrown.
    2. The data you write to the stream is appended to the existing file.
    3. The existing file is replaced with the data you write to the stream.
  2. What two primitive types are interchangable when you're working with streams ?
    1. byte and boolean
    2. char and int
    3. byte and char
  3. In Java, what is the maximum value of a byte variable and the maximum value of an unsigned byte in a stream ?
    1. Both are 255
    2. Both are 127
    3. 127 for a byte variable and 255 for an unsigned byte

Answers

  1. C. That's one of the things to look out for when using output streams, you can easily wipe out existing files. Constructors can use a Boolean vale to append data to a file instead of replacing the entire thing.
  2. B. Because Java represents a char internally as an integer value, you often can use the two interchangeably in method calls and other statements.
  3. C. The byte primitive data type has values ranging from -128 to 127, whereas an unsigned byte can range from 0 to 255.

Certification Practice

  1. Will this program successfully store a line of console input in the String object named command ?
    1. Yes.
    2. No, because a buffered input stream is required to read console input.
    3. No, because it won't compile successfully.
    4. No, because it reads more than one line of console input.

Exercise