Title: PrintStream, MyOutput, MyInput
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

PrintStream, MyOutput, MyInput

1. PrintStreams - More Convenient Output Buffering Mechanism. So far most of our output has been done with:
System.out.println (.....) or
System.out.print(....)

The println, and print family of routines provide a higher level way to generate output than write one or more bytes. System.out.println normally sends output to your screen, but you can have the println, print family of routines available for any output device : screen, file, web_browser, etc.

System.out is an instance of the PrintStream class. Suppose I want to write to a file named myfile.text with a print, println interface. Here is a snippet of code that will do it:


    // the following methods can throw IOException so add throws IOException to
    // the method definition.
    FileOutputStream f = new FileOutputStream("myfile.text");
    PrintStream myout = new PrintStream(f);

    myout.println("My age is " + age);
    myout.print("My name is " + name);


2. Sample PrintStream code created in the Video:


package IO;

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

public class TestingPrintstream {


    public static void main(String[] args) {
        FileOutputStream fs = null;

        try {
            fs = new FileOutputStream("fo.txt");
            PrintStream ps = new PrintStream(fs);

            ps.println("Testing PrintStream");
            ps.println("Last line");


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if (fs != null)
                try {
                    fs.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

    }

}



3. MyOutput class - Consider the following MyOutput class that has 2 constructors:
MyOutput()
MyOutput(String filename)

This code has the property if you use the print and println methods of a class created with the first constructor, you send output to the screen. If you use the second constructor, you send output to the file contained in the filename parameter.

package tools;
import java.io.*;

public class MyOutput {
// If a file is not passed in, we will open up a PrintStream
// created from System.out

   PrintStream out = System.out;
   String fileName=null;

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

// output goes to a file
public MyOutput(String file)
   {
   fileName = file;
   open2(fileName, false);
   }

// If append = true, then the output file will be appended as
// opposed to overwriting from the beginning.
public MyOutput(String file, boolean append)
   {
   fileName = file;
   if (!open2(fileName, append))
       System.out.println("Defaulting to Terminal Screen");
   }


public boolean open(String arg)
   {
        return open2(arg, false);
    }


public boolean open2(String arg, boolean append)
   {
       try {
               String file = arg;
               if (file.length() > 0)
                   {
                        FileOutputStream fw;
                        if (append)
                           fw = new FileOutputStream(file, true);
                        else
                           fw = new FileOutputStream(file);
                       out =    new PrintStream(fw);
                   }
               return true;
       }
       catch (FileNotFoundException e) {
           System.out.println("File Not Found Exception in get" +
                   e.getMessage());
           return false;
       }
   }

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

public void print(String str)
   {
      out.print(str);
   }
public void close()
{
   out.close();
}
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();
   }
}


4. Scanner class - Demo Scanner class as an input buffering class for files. Look up the definition in online help to figure out how to do this. The Scanner class was added to Java around release 1.4. Before that time, I needed something like the Scanner class and in the following sections you can see an alternative to the Scanner class.
5. Converting an InputStream class to a Reader class - Some of the better buffering mechanisms in the Java I/O classes live in the char Unicode world. For example the BufferedReader class has one method (readLine) which is very handy. The readLine routine allows you to read one line of input at a time. If you take a careful look at the MyInput class we have been using, you will find that it is using the readLine routine in the BufferedReader class.

Most devices, however, present a byte stream interface. For example
System.in is an InputStream.

If you have a byte stream but you want a Reader class so you can use a BufferedReader, then you want know about the conversion class:
InputStreamReader. Here is a snippet of code from the MyInput class that demonstrates the process:


    InputStream myInTemp = System.in;
    InputStreamReader myReader = new InputStreamReader(myInTemp);
    BufferedReader myIn = new BufferedReader(myReader);

    String str;
    str = myIn.readLine();



6. MyInput class - We have been using the MyInput class, but we haven't pointed out some of its characteristics:

package tools;
import java.io.*;

public class MyInput {
// If a file is not passed in, we will open up a Buffered Reader
// created from System.in

   InputStreamReader instream = new InputStreamReader(System.in);
   BufferedReader in = new BufferedReader(instream);
   String fileName=null;

// read from keyboard
public MyInput()  {
   }

//read from file f
public MyInput(String f)
   {
     fileName = f;
     if (!open(fileName))
         System.out.println("Defaulting to reading from keyboard");
   }
public boolean open(String file)
   {
       try {
               if (file.length() > 0)
                   {
                       FileReader fr = new FileReader(file);
                       in =    new BufferedReader(fr);
                   }
               return true;
       }
       catch (FileNotFoundException e) {
           System.out.println("File Not Found Exception in get");
           return false;
       }
   }

public void close()
{
   try {
       in.close();
       }
   catch (IOException e){
       System.out.println("IO Exception on close call");
       }
}

protected void finalize()
{
    close();
}

public String get()
   {
       try {
               return in.readLine();
       }
       catch (FileNotFoundException e) {
           System.out.println("File Not Found Exception in get");
           return null;
       }
       catch(IOException e) {
           System.out.println("IO Exception in get");
           return null;
       }
   }

public int getInt()
{
    String str = get();
    if (str != null)
    {
       try {
            return Integer.parseInt(str);
            }
       catch (NumberFormatException e) { /* Do Nothing */}
    }
    System.out.println("Bad int input");
    return -1;
}

public static void main(String args[])  {
       MyInput input;
       String str;

       if (args.length > 0)
           input = new MyInput(args[0]);
       else
           input = new MyInput();

       do {
           str = input.get();
           if (str != null)
           {
               System.out.println(str);
                   if (str.equals("####"))
                       break;
           }
       } while (str != null);

       input.close();

   }
}


7. One more example using Scanner and PrintStream - Since we do have the Scanner, and PrintStream it is useful to show how these can be useful to you. So I have one last example for this set of notes:



import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

public class IO_Test {

    void FileReadMethod(String filename)
    {
        File f = new File(filename);
        try {
            Scanner scan = new Scanner(f);
            while (scan.hasNextLine())
            {
                String s = scan.nextLine();
                System.out.println(s);
            }
            scan.close();
        } catch (FileNotFoundException e) {
            System.out.println(" Error: "+e + " "+ filename);
            e.printStackTrace();
        }
    }




    void FileCopy(String filename, String outFile)
    {
        File f = new File(filename);
        File fo = new File(outFile);

        try {
            Scanner scan = new Scanner(f);
            PrintStream ps = new PrintStream(fo);


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

        } catch (FileNotFoundException e) {
            System.out.println(" Error: "+e + " "+ filename);
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {


        IO_Test it = new IO_Test();
        it.FileCopy("src/IO_Test.java", "junk.txt");

        System.out.println("Copy finished: src/IO_Test.java --> junk.txt");

        it.FileReadMethod("junk.txt");

    }

}




Last Updated: July 29, 2013 0:24 AM