import java.io.*;

/* All the methods in this class must throw IOException because they
 * either directly or indirectly call an IO method that could fail
 * for a variety of reasons. We don't plan to do anything special if
 * an error occurs, so we don't need to catch and handle the exception.
 * These methods just pass it on.
 */

public class IOExample {
  public static void main(String[] args) throws IOException {
    keyboardInput();
    fileOutput("temp.txt");
    fileInput("temp.txt");
  }
   
  public static void keyboardInput() throws IOException{
    // Reading input from the keyboard 
    BufferedReader br = new BufferedReader(
                            new InputStreamReader(System.in));
    // Prompt for some input
    System.out.println("Please enter a string:");
    String line = br.readLine();
    System.out.println ("I read: " + line);
    
    System.out.println("Please enter an integer");
    int a = Integer.parseInt(br.readLine());
    System.out.println("Please enter a floating point number");
    double b = Double.parseDouble(br.readLine());
    System.out.println("Sum of the two numbers is " + (a + b));
  }
  
  /* Read integers from a file and print out their sum*/
  public static void fileInput(String filename) throws IOException{
    BufferedReader br = new BufferedReader(
                            new FileReader(filename));
    
    int sum = 0;
    String line = br.readLine();
    while(line != null) {
      int num = Integer.parseInt(line);
      sum += num;
      System.out.print(num + " ");
      line = br.readLine();
    }
    System.out.println("");
    System.out.println("sum of the integers is " + sum);
  }
  
  /* Write an array of integers to a file */
  public static void fileOutput(String filename) throws IOException {
    PrintStream ps= new PrintStream(new FileOutputStream(filename));
    int[] a = {10, 9, 8, 7, 6};

    for(int i = 0; i < a.length; i++) {
      ps.println(a[i]);
    }
  }
}