Homework 04

 

Task 1.

Read the following examples code fragments. Pay attention to the comments explaining the code. Compile and run the three programs.

 

a. writing to a text file

import java.io.*; //for PrintWriter, BufferedWriter, FileWriter

 

//write to a text file

class WriteToTextFile

{

 

public static void main(String args[])

{

    String logFile = "log.txt";

 

    try {

        // prepare the output file so that you can use print/ln()

        PrintWriter log = new PrintWriter(new BufferedWriter(

                 new FileWriter(logFile)));

 

        // write to the text file similar to System.out

        log.print(10 + " times ");

        log.println("Hello");

 

        //close log file

        log.close();

    }

    catch (IOException e) { //catch file-related errors

        e.printStackTrace();   

    }

}

 

} 

 

b. reading from a text file

import java.io.*; // for Scanner

import java.util.*;  // for File

 

//write to a text file

class ReadFromTextFile

{

 

public static void main(String args[])

{

    String logFile = "log.txt";

 

    try {

        //prepare file to read

        Scanner scanner = new Scanner(new File(logFile));

 

        //read a int and a string from the file

        int i = scanner.nextInt();

        String s = scanner.nextLine();

 

        System.out.println("i = " + i + ", s = " + s);

    }

    catch (Exception e) { //catch file-related errors

        e.printStackTrace();

    }

}

}

 

c. reading command-line parameters

//read command-line parameters

//This program should be run from command-line prompt

// e.g. c:\>java ParameterList this is my arguments list

class ParameterList

{

 

public static void main(String args[])

{

    System.out.println("Command-line arguments are:");

    for (int i = 0; i< args.length; i++)

     System.out.println("args[" + i +"]: "+ args[i]);

}

}

 

Task 2 (to be submitted in writing).

Write a program that read a series of 10 integers from a text file and write them to another text file in the reverse order. The names of the input and output files should be given as command-line parameters. For example, the command

      java Task2Hw4 test1.in test1.out

should get Task2Hw4 to read input from file test1.in and write output to the file test1.out. (the file names MUST NOT be hard-coded in the program).

 

Task 3.

Read the package guide at

http://www.yoda.arachsys.com/java/packages.html

Organize your .java files.

 

Task 4 (to be submitted in writing).

Put the program from task2 to package hw04. Describe how you modify the code of Task2Hw4.java to make it a part of the package, and how you compile that file from command-line prompt (not from NetBean/Eclipse).