Title: PrintStream Scanner Examples
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

PrintStream Scanner Examples

In cps161 we had a lot of code that had statements like:

System.out.println("Enter some input");
Scanner keyboard = new Scanner(System.in);

To better understand this, we should look at the System class in the java.lang package to find the following:


static PrintStream 	err;      //The "standard" error output stream.
static InputStream 	in;       //The "standard" input stream.
static PrintStream 	out;      //The "standard" output stream.


In the Unix tradition applications have always had the "standard I/O streams" of stderr, stdin, and stdout. By default stderr and stdout default to the screen and stdin defaults to the keyboard. The java equivalents are the static classes err, in, and out.

Also in Java there are two abstract classes that provide a base class for many of our Input/Output work that we wish to do in Java:

InputStream - Notice the primitive interface working with bytes .... not too convenient usually

OutputStream - Also a primitive interface with bytes

We can look them up in the Java Documentation. To create InputStreams, and OutputStreams associated with the File System, you will need to used the classes:

FileInputStream, FileOutputStream - Look these up ... there are many constructors.

Note that Scanners and PrintStreams can be used in other situations as well. For example, Internet Socket connections.

Output Examples:

PrintStream is much easier to work with (because of println, print) than writing bytes. Take a look at the documentation for PrintStream and see the different constructors.

PrintStream, OutputStream, FileOutputStream examples:

Run this program and check out the file created


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;


public class PrintStreamExamples {

    private void output_using_print_stream(String[] stuff, PrintStream ps)
    {
        for (int i=0; i < stuff.length; i++)
        {
            /*
             * This is what would have done in Cps161
            System.out.print(i);
            System.out.println(": " + stuff[i]);
             */
            ps.print(i);
            ps.println(": " + stuff[i]);
        }
    }

    public void write_to_screen(String[] stuff)
    {
        output_using_print_stream(stuff, System.out);
    }

    public void write_to_file(String[] stuff, String filename, boolean concatenate_to_end_of_file)
    {
        if (filename == null)
            output_using_print_stream(stuff, System.out);


        try {
            // Note that FileOutputStream(filename) is equivalent to FileOutputStream(filename, false)
            FileOutputStream fs = new FileOutputStream(filename, concatenate_to_end_of_file);
            PrintStream ps = new PrintStream(fs);
            output_using_print_stream(stuff, ps);
            ps.close();
        }
        catch (FileNotFoundException e) {
            //e.printStackTrace();  // This goes to the err PrintStream ... sometimes confusing
            e.printStackTrace(System.out);
        }


    }



    public static void main(String[] args) {
        PrintStreamExamples pse = new PrintStreamExamples();
        String[] stuff = {"apple", "orange", "pear", "bannana", "strawberry"};

        System.out.println("write_to_screen");
        pse.write_to_screen(stuff);

        System.out.println("*********** write_to_file - no concatenation ****************");
        pse.write_to_file(stuff, "file_overwrite.txt", false);
        pse.write_to_file(stuff, "file_overwrite.txt", false);


        System.out.println("*********** write_to_file - WITH concatenation ****************");
        pse.write_to_file(stuff, "file_concatenation.txt", true);
        pse.write_to_file(stuff, "file_concatenation.txt", true);

        System.out.println("bye");



    }

}



MyOutput

The following MyOutput class is provided if you would like a handy dandy routine that makes it possible to conveniently switch between writing to the screen and a file. This is often done in Unix and is called "output redirection".


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class MyOutput {
    // If a file is not passed in, we will use System.out

    PrintStream out = System.out;

    // output goes to screen
    public MyOutput()  {
    }

    // output goes to a file
    public MyOutput(String filename)
    {
        this(filename, false);
    }

    // If append = true, then the output file will be appended as
    // opposed to overwriting from the beginning.
    public MyOutput(String filename, boolean append)
    {
        try {
            if (filename != null && filename.length() > 0)
            {
                FileOutputStream fw;
                if (append)
                    fw = new FileOutputStream(filename, true);
                else
                    fw = new FileOutputStream(filename);
                out =    new PrintStream(fw);
            }
        }
        catch (FileNotFoundException e) {
            System.out.println("Defaulting to Screen: ....File Not Found Exception: " + e);
        }
    }

    public void println (String str) {
        out.println(str);
    }

    public void print(String str)
    {
        out.print(str);
    }
    public void close()
    {
        if (out != System.out)
            out.close();
    }
    // If someone forgets to close the file, finalize is called when the garbage collector collects
    // this object.   Kind of late in most cases, but maybe better than nothing.
    protected void finalize()
    {
        close();
    }

    public static void main(String args[])  {
        // myout1 will write to screen
        MyOutput myout1 = new MyOutput() ;

        //myout2 will write to file junk.txt
        MyOutput myout2 = new MyOutput("junk.txt");

        myout1.println("First Line"); // write to screen
        myout2.println("First Line"); // write to junk.txt

        myout1.println("Second Line"); // write to screen
        myout2.println("Second Line"); // write to junk.txt

        myout1.close();
        myout2.close();
    }
}


Input Examples - using Scanner with Files

Instead of passing System.in which is an InputStream, we will use FileInputStream to create an InputStream associated with a file.

Note that many of the techniques used with the Scanner in cps161 work with Files.

However, an additional need is detecting the end of file. So we will finding ourselves calling routines like:

- hasNextLine
- hasNextInt
- hasNextDouble
- hasNext
- etc.

Check out the following example:

ScannerReadFromFile.java


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class ScannerReadFromFile {

    private FileInputStream getFileInputStream(String filename)
    {
        FileInputStream fileInputStream=null;
        try {
            fileInputStream = new FileInputStream(filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace(System.out);
        }

        return fileInputStream;
    }

    public void lineByLineRead(String filename)
    {
        FileInputStream fileInputStream =getFileInputStream(filename);
        if (fileInputStream == null)
            return;

        Scanner scanner = new Scanner ( fileInputStream);

        while (scanner.hasNextLine())
        {
            String s = scanner.nextLine();
            System.out.println(s);
        }

        scanner.close();
        System.out.println("*********  Done with lineByLineRead ******");
    }
    public void numbersRead(String filename)
    {
        FileInputStream fileInputStream =getFileInputStream(filename);
        if (fileInputStream == null)
            return;

        Scanner scanner = new Scanner ( fileInputStream);
        int count=0;

        while (scanner.hasNextInt())
        {
            int x = scanner.nextInt();
            count += 1;
            System.out.printf("%5d", x);
            if (count % 10 == 0)
                System.out.println();
        }

        scanner.close();
        System.out.println();
        System.out.println("*********  Done with numbersRead ******");
    }

    public void readMixed(String filename)
    {

        FileInputStream fileInputStream =getFileInputStream(filename);
        if (fileInputStream == null)
            return;

        Scanner scanner = new Scanner ( fileInputStream);

        while (scanner.hasNextInt())
        {
            int age = scanner.nextInt();
            double weight = scanner.nextDouble();
            scanner.nextLine();  // Throw away the remainder of the line
            String fullName = scanner.nextLine();

            System.out.println(fullName + " age=" + age + " weight="+weight);
        }
        scanner.close();
        System.out.println("*********  Done with readMixed ******");
    }


    public static void main(String[] args) {
        ScannerReadFromFile srf = new ScannerReadFromFile();

        srf.lineByLineRead("lineByLine.txt");

        srf.numbersRead("numbers.txt");

        srf.readMixed("mixed.txt");

    }

}



You will need some input files that need to be placed at the "project" level:

lineByLine.txt


An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
The objects can be read (reconstituted) using an ObjectInputStream.
Persistent storage of objects can be accomplished by using a file for the stream.
If the stream is a network socket stream, the objects can be reconstituted on another host or
in another process.

Only objects that support the java.io.Serializable interface can be written to streams.
The class of each serializable object is encoded including the class name and signature of the class,
the values of the object's fields and arrays, and the closure of any other objects referenced from
the initial objects.



numbers.txt


1 2 3
400 600 546  890 1122  45
5
678  67 45
1
222 555


mixed.txt


12 80.1
Little Indian
50 230.4
Big George Militzer
65 206
Fred the Slugger


Text File Copying using the Scanner and PrintStream classes

I have put the above concepts together to produce a routine for copying files.


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;


public class CopyTextFileExample {

// the copy will normally be between the inputFile and the outputFile.  If anything goes wrong,
//  or the user passes in null for either for these entries, then we default to System.in and/or System.out

    void fileCopy(String inputFile, String outputFile)
    {
        Scanner scanner = null;
        PrintStream ps = System.out;
        InputStream inputStream = System.in;
        OutputStream outputStream = null;

        try {
            if (outputFile != null)
                outputStream = new FileOutputStream(outputFile);
        } catch (FileNotFoundException e) {
            System.out.println(" Unable to open output file: "+ outputFile + "  Defaulting to Screen");
        }

        try {
            if (inputFile != null)
                inputStream = new FileInputStream(inputFile);
        } catch (FileNotFoundException e) {
            System.out.println(" Unable to open input file: "+ inputFile + "  Defaulting to Keyboard");
        }

        scanner = new Scanner(inputStream);
        if (outputStream != null)
            ps = new PrintStream(outputStream);

        while (scanner.hasNextLine())
        {
            String s = scanner.nextLine();
            ps.println(s);
        }

        scanner.close();
        if (ps != System.out)
            ps.close();

    }

    public static void main(String[] args) {

        CopyTextFileExample cfe = new CopyTextFileExample();
        cfe.fileCopy("src/CopyTextFileExample.java" ,  "copiedFile.java");

        cfe.fileCopy("copiedFile.java", null /* to the screen */);

    }

}



Last Updated: January 10, 2014 1:45 AM