Programmierpraktikum




Claudius Gros, SS2012

Institut für theoretische Physik
Goethe-University Frankfurt a.M.

Input / Output Streams

Java I/O streams

stream from/to everywhere

transmit all kind of data






java.io



IO - communiation with the world

modern programming

exception handeling mandatory for IO


byte streams

IO byte per byte



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//  normally just use   import java.io.*;

public class CopyBytes {
  public static void main(String[] args) throws IOException {
// what happens if you would just use
// public static void main(String[] args) {

   FileInputStream in = null;
   FileOutputStream out = null;

   in = new FileInputStream("input.txt");
   out = new FileOutputStream("output.txt");
   int c;

// --- start loop over all bytes in input file
    while ((c = in.read()) != -1) 
      out.write(c);

// --- all reading has been done - close streams
    if (in != null)    in.close(); 
    if (out != null)  out.close(); 
  }  // end of CopyBytes.main()
}  // end of CopyBytes

import java.io.*;

public class AppendBytes {
public static void main(String[] args)  // no exception thrown
  {
  try {
      FileInputStream inStream = new FileInputStream("input.txt");
      FileOutputStream outStream = new FileOutputStream("output.txt",true);  // append
//               are equivalent:   new FileOutputStream("output.txt",false);
//                                 new FileOutputStream("output.txt");
//                                 new FileOutputStream("output.txt",(1==2));
      int c;
      while ((c = inStream.read()) != -1) 
        outStream.write(c);
      } catch(IOException e)
        {
        System.out.println(e.toString());
        }
  }  // end of AppendBytes.main()
}  // end of AppendBytes

This is an text input file
with a picture
     
    ,,,,,
  *      *
 |* o  o *|
  *      *
   \ == /
     ..

formatted output

import java.io.*;

public class FormattedOutput {
public static void main(String[] args) 
  {
  try {
      PrintWriter myOutput = new PrintWriter("output.txt");
      for (int i=0;i<8;i++)
        myOutput.printf("%2d modulo 3 is %2d\n",i,i%3);
      myOutput.flush();     // sent buffer to file
      } catch(IOException e)
        {
        System.out.println(e.toString());
        }
  }  // end of FormattedOutput.main()
}    // end of FormattedOutput

buffered input

buffering

buffered input with formatted output

buffered and formatted ouput

import java.io.*;

public class BufferedOutput {
public static void main(String[] args) 
  {
  try {
      PrintWriter myOutput = new PrintWriter(                      // for formatting
                                new BufferedWriter(                // for buffering           
                                   new FileWriter("output.txt"))); // ouput stream

      for (int i=0;i<8;i++)
        myOutput.printf("%2d modulo 5 is %2d\n",i,i%5);
      myOutput.flush();     // sent buffer to file

      } catch(IOException e)
        {
        System.out.println(e.toString());
        }
  }  // end of BufferedOutput.main()
}    // end of BufferedOutput

IO streams as arguments in function calls

import java.io.*;

public class PrintWriterDemo {

/** Use a single facility to send data to different streams,
  * note the mandatory exception handling.
  */
static void printToStream(PrintWriter myOutput, String text)
            throws IOException
 {
 myOutput.printf("this is the text: %s\n",text);
 }

/** Always use buffered IO, it never hurts.
  */

public static void main(String args[]) 
  {
  try {
    PrintWriter toFile =
      new PrintWriter(new BufferedWriter(
                      new FileWriter("printWriterDemo.out")));
    PrintWriter toConsole =  new PrintWriter(System.out, true);

  PrintWriterDemo.printToStream(toFile,"sending data to file");
  PrintWriterDemo.printToStream(toConsole,"sending log data to console");

  toFile.close();
  toConsole.close();
      } catch (IOException e) { e.printStackTrace(); }
  } // end of PrintWriterDemo.main()
} // end of class PrintWriterDemo

scientific data files

9
Mercury 0.0553 4880 5.43 0.000 58.81 d 0.387 87.97 d 0.2056 7.0 0.1
Venus 0.815 12104 5.20 0.000 243.69 d 0.723 224.70 d 0.0068 3.4 177.3
Earth 1.000 12742 5.52 0.0034 23.9345 h 1.000 365.26 d 0.0167 0.00 23.45
Mars 0.107 6780 3.93 0.0065 24.623 h 1.524 686.98 d 0.0934 1.85 25.19
Jupiter 317.83 139822 1.33 0.0649 9.925 h 5.203 11.86 y 0.04845 1.305 3.12
Saturn 95.162 116464 0.687 0.098 10.50 h 9.539 29.46 y 0.05565 2.489 26.73
Uranus 14.536 50724 1.32 0.023 17.24 h 19.182 84.01 y 0.0472 0.773 97.86
Neptune 17.147 49248 1.64 0.017 16.11 h 30.06 164.79 y 0.00858 1.773 29.56
Pluto 0.0021 2274 2.05 0.0 6.405 d 39.53 247.68 y 0.2482 17.15 122.46

scanning data input files

scanning for data: double, int, ...

import java.io.*;
import java.util.Scanner;

public class DataInput {
public static void main(String[] args)
  {
  try {
      Scanner myScanner = new Scanner(
                              new FileInputStream("planetsData.list"));

// --- skippling initial comments
      boolean readingComments = true; 
      while (readingComments)             
          readingComments = false;

// --- reading data
      int nData = myScanner.nextInt();
      String name;
      double mass;
      int diameter;

      while (myScanner.hasNext()) 
        {
        name     = myScanner.next();
        mass     = myScanner.nextDouble();
        diameter = myScanner.nextInt();

        for (int i=0;i<10;i++) myScanner.next();  // skipping rest of line
        }

      } catch(IOException e)
        {
        System.out.println(e.toString());
        }
  }  // end of DataInput.main()
}    // end of DataInput

output of objects

object output streams

import java.io.*;

public class ObjectsIo {
public static void main(String[] args)  
  {
// ***
// *** generate objects and write objects to file
// ***
  String[] stringArrayObject = {"This","is","an","array","of","strings"};
  int[] intArrayObject = {4444,333,22,1};
  try {
      ObjectOutputStream myOutput = new ObjectOutputStream(
                                    new FileOutputStream("containsObject.txt"));

      myOutput.writeObject(stringArrayObject);
      myOutput.writeObject(intArrayObject);

      } catch(IOException e)
        {
        System.out.println(e.toString());
        }
// ***
// *** read objects from file
// ***
  try {
      ObjectInputStream myInput = new ObjectInputStream(
                                  new FileInputStream("containsObject.txt"));

      Object obj = null;
      while ((obj = myInput.readObject()) != null) 
        {
        if (obj instanceof String[])      // String array ?
          {
          String[] ss = (String[])obj;    // casting Object to String[]
          for (int j=0;j<ss.length;j++)
            System.out.printf("%s ",ss[j]);
          System.out.printf("\n"); 
          }
        if (obj instanceof int[])         // int array ?
          {
          int[] ii = (int[])obj;          // casting Object to int[]
          for (int j=0;j<ii.length;j++)
            System.out.printf("%d ",ii[j]);
          System.out.printf("\n"); 
          }
        }
      
      } catch (EOFException ex) { // EOF exception
            System.out.println("End of file reached.");
      } catch(IOException e)
        {
        System.out.println(e.toString());
        } catch (ClassNotFoundException e) 
          {
          System.out.println(e.toString());
          } 

  }  // end of ObjectsIo.main()
}    // end of ObjectsIo

exercise: IO and OOP

Write a program for object oriented input/output.

directory listings

import java.util.*;
import java.io.*;
import java.math.*;

public class DirectoryHandling {

/** Give directory path as argument.
  */
public static void main(String args[]) {

// *** 
// *** open file handler / directory listing
// *** 
  String inputDirPath = null;
  if (args.length==1)
    inputDirPath = args[0];                           // directory path
  else
    if (args.length==0)
      inputDirPath = System.getProperty("user.dir");  // working directory
    else
      {
      System.out.printf("number of arguments must be 0/1 and not %d\n", 
                        args.length);
      return;           // exit main()
      }
  
  File inputDir = new File(inputDirPath);   // open file or directory
  String[] inputDirFiles = null;
  if (inputDir.isDirectory())               // got a directory?
    inputDirFiles = inputDir.list();
  else
    {
    System.out.println("input not a directory: " + inputDirPath);
    return;           // exit main()
    }

// *** 
// *** (limited) output of directories/files found
// *** 
  String fileSeparator = System.getProperty("file.separator");
                       // is "/" on UNIX and "\" on Windows
//
  System.out.println(" ");
  System.out.println("files and directories found in: " + inputDirPath);
  System.out.println(" ");
  for (int i=0;i<Math.min(10,inputDirFiles.length);i++)
    {
    String fullPath = inputDirPath + fileSeparator + inputDirFiles[i];
    File listFile = new File(fullPath)        ;   // open file or directory
    if (listFile.isFile())                        // got a file?
      System.out.println("file: " + fullPath);
    else
      System.out.println(" dir: " + fullPath);
   }

  }  // end of DirectoryHandling.main()
}    // end of DirectoryHandling