Complete Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

No, it only reminds the user of the correct order. The user is expected to start the program without arguments to get a reminder.

Complete Program

The class File could be used to check if a file already exists (and then not used as the destination). The program could be improved by using that class. But for now, here is the complete program:

import java.io.*;
class CopyBytes
{
  public static void main ( String[] args ) 
  {
    DataInputStream  instr;
    DataOutputStream outstr;
    if ( args.length != 3 || !args[1].toUpperCase().equals("TO") )
    {
      System.out.println("java CopyBytes source to destination");
      return;
    }

    try
    {
      instr = 
        new DataInputStream(
          new BufferedInputStream(
            new FileInputStream( args[0] )));
      outstr = 
        new DataOutputStream(
          new BufferedOutputStream(
            new FileOutputStream( args[2] )));

      try
      {
        int data;
        while ( true )
        {
          data = instr.readUnsignedByte() ;
          outstr.writeByte( data ) ;
        }
      }
      catch ( EOFException  eof )
      {
        outstr.close();
        instr.close();
        return;
      }
    }

    catch ( FileNotFoundException nfx )
    {
      System.out.println("Problem opening files" );
    }
    catch ( IOException iox )
    {
      System.out.println("IO Problems" );
    }

  }
}

A computer's operating system comes with a file copy command, so there is no practical use for this program. But it is a foundation for many programs that are of practical use. Various data transformations can be done by slipping in some statements between the reading and the writing of the byte.

QUESTION 22:

(Thought question: ) What modification will change this program so that it counts the number of bytes in a file?