Solved

Copying and concatenating from one file to another

Posted on 2004-10-30
558 Views
Last Modified: 2010-04-15
I am trying to perform 3 different functions: 1. write a program that copies one file to another file / 2. write a program that concatenates the contents of many files into just one file and / 3. write a program that searches all files specified on the command line and prints out all lines containing a keyword.  So far here is the code:

----- 1. COPY FILE -----
import java.io.*;
public class CopyFile
{
    public static void main(String args[]) throws IOException
    {
        int a;
       
        if (args.length !=2)
        {
            System.out.println("Usage: java CopyFile fromFile to File");
        }   // end if stmt
        else
        {
       
        BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
        BufferedReader in = new BufferedReader(new FileReader(inputFile));
         
        File inputFile = new File(args[0]);
        File outputFile = new File(args[1]);
       
            while ((a = in.read()) != -1)
            {
              out.write(a);
            }   // end while loop
       
            in.close();
            out.close();
       
        }   // end else
       
    }   // end main
   
}   // end  class copyfile
----------------------------------------
----- 2. CATFILE -----
import java.io.*;
public class CatFile
{
    public static void main(String args[]) throws IOException
    {
        int argNumber;
        int count;
        int a;
         
              if (args.length < 2)
                    {
                           
                        System.out.println("Usage: java CopyFile fromFile to File");
                         
                    }   // end if stmt
              else
                    {

                      argNumber = args.length - 1;

                      File outputFile = new File(args[argNumber]);

                      BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));                         

                      for (count = 0; count < argNumber; count++)
                      {

                     File inputFile = new File(args[count]);
   BufferedReader in = new BufferedReader(new FileReader(inputFile));                                          
       
                                    while ((a = in.read()) != -1)
                           {  
                                     
                                        out.write(a);
                                       
                                           }  // end while stmt
                               
                       in.close();
                               
                      }   // end for stmt
                         
                           out.close();
                         
                 }      // end else stmt
          }      // end main
}      // end class CatFile
--------------------------------------------------
----- 3. FINDFILE -----
import java.io.*;

public class Find
{

   public static void main(String[] args) throws IOException
   {
if (args.length < 2)
{
System.out.println("correct usage is: java Find searchword
TextFile1.txt
TextFile2.txt");
}


else
{
   int argLength = args.length;

   int len = args[0].length();

  int count;

  String searchMe = args[0];

for (count = 1; count < argLength; count++)

   {

      File inputFile = new File(args[count]);

      BufferedReader input = new BufferedReader(new
      FileReader(inputFile));

      String text;

      while((text = input.readLine()) != null)

      {

       int i = 0;

       for (i=0; i < text.length(); i++)
      {


        if(text.regionMatches(i, searchMe, 0, len))

        {

       System.out.println(args[count] + ": " + text);
        }//end if
       } //end while matches
      }//end readline while
    }//end for count
}//ends if
  }//ends main
}//ends class SearchFile
-------------------------------------------
For some reason, only CatFile.java compiles but the other two do not and I don't know what the problem is.  Any help on this would greatly be appreciated!  Thank you!!!
0
Question by:adidas7fire
    8 Comments
     
    LVL 15

    Accepted Solution

    by:
    Here's for the CopyFile.java

    import java.io.*;

    public class CopyFile
    {
        public static void main(String args[]) throws IOException
        {
            int a;
           
            if (args.length !=2)
            {
                System.out.println("Usage: java CopyFile fromFile to File");
            }   // end if stmt
            else
            {
            File inputFile = new File(args[0]);
            File outputFile = new File(args[1]);

            BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
            BufferedReader in = new BufferedReader(new FileReader(inputFile));
           
                while ((a = in.read()) != -1)
                {
                  out.write(a);
                }   // end while loop
           
                in.close();
                out.close();
           
            }   // end else
        }   // end main
    }   // end  class copyfile
    0
     
    LVL 15

    Expert Comment

    by:Javatm
    Here's for the Find.java

    import java.io.*;

    public class Find
    {

       public static void main(String[] args) throws IOException
       {
          if (args.length < 2)
          {
          System.out.println("correct usage is: java Find searchword " +
                    "TextFile1.txt TextFile2.txt");
          }

          else {

             int argLength = args.length;
             int len = args[0].length();
            int count;

            String searchMe = args[0];

          for (count = 1; count < argLength; count++) {

                File inputFile = new File(args[count]);

                BufferedReader input = new BufferedReader(new
                FileReader(inputFile));

                String text;

                while((text = input.readLine()) != null) {

                 int i = 0;

                 for (i=0; i < text.length(); i++) {

                    if(text.regionMatches(i, searchMe, 0, len)) {
                System.out.println(args[count] + ": " + text);
                    }//end if

                 } //end while matches
                }//end readline while
              }//end for count
          }//ends if
      }//ends main
    }//ends class SearchFile
    0
     
    LVL 15

    Expert Comment

    by:Javatm
    I actually saw some wrong things on the codes.

    1. CopyFile.java :
    The File declaration should come up 1st like :

    File inputFile = new File(args[0]);
    File outputFile = new File(args[1]);
    BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
    BufferedReader in = new BufferedReader(new FileReader(inputFile));

    2. Find.java :

    The System.out.println was not connected so it should be :
    System.out.println("correct usage is: java Find searchword " + "TextFile1.txt TextFile2.txt");

    The complete fix was on my 1st 2 comments above !.

    Hope that helps . . .
    Javatm
    0
     

    Author Comment

    by:adidas7fire
    Wow!  I'm such a retard.  I see what I left out.  Thanks for your help, Javatm.  I do have another question for you.  The question is when I am at the command prompt and I'm trying to use the copy function such as this:

    ....my documents> java CopyFile report.txt report.sav

    to copy the information from one file to another, I tried it but nothing shows up.  I made a generic .txt file with nothing on the file... I just named it and saved it.  Why doesn't anything copy into that file?  Thanks again for your help!
    0
     
    LVL 15

    Expert Comment

    by:Javatm
    Copying a certain file is not as easy as you think. I'll give you several codes that will help you.

    1. Copying a File :

    import java.io.*;

    /**
     * This class is a standalone program to copy a file, and also defines a
     * static copy() method that other programs can use to copy files.
     **/
    public class FileCopy {

      public static void main(String[] args) {

        if (args.length != 2)    
          System.err.println("Usage: java FileCopy <source file> <destination>");

        else {
         
          try { copy(args[0], args[1]); }
          catch (IOException e) { System.err.println(e.getMessage()); }
        }
      }

      /**
       * The static method that actually performs the file copy.
       * Before copying the file, however, it performs a lot of tests to make
       * sure everything is as it should be.
       */
      public static void copy(String from_name, String to_name) throws IOException{

        File from_file = new File(from_name);
        File to_file = new File(to_name);

        if (!from_file.exists())
          abort("FileCopy: no such source file: " + from_name);

        if (!from_file.isFile())
          abort("FileCopy: can't copy directory: " + from_name);

        if (!from_file.canRead())
          abort("FileCopy: source file is unreadable: " + from_name);

        if (to_file.isDirectory())
          to_file = new File(to_file, from_file.getName());

        if (to_file.exists()) {

          if (!to_file.canWrite())
          abort("FileCopy: destination file is unwriteable: " + to_name);

          System.out.print("Overwrite existing file " + to_name + "? (Y/N): ");
          System.out.flush();

          BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
          String response = in.readLine();

          if (!response.equals("Y") && !response.equals("y"))
            abort("FileCopy: existing file was not overwritten.");
        }
        else {  

          // if file doesn't exist, check if directory exists and is writeable.
          // If getParent() returns null, then the directory is the current dir.
          // so look up the user.dir system property to find out what that is.

          String parent = to_file.getParent();
          if (parent == null) parent = System.getProperty("user.dir");
          File dir = new File(parent);        

          if (!dir.exists())
            abort("FileCopy: destination directory doesn't exist: " + parent);

          if (dir.isFile())
            abort("FileCopy: destination is not a directory: " + parent);

          if (!dir.canWrite())
            abort("FileCopy: destination directory is unwriteable: " + parent);
        }
       
        FileInputStream from = null;  
        FileOutputStream to = null;  

        try {

          from = new FileInputStream(from_file);  
          to = new FileOutputStream(to_file);    
          byte[] buffer = new byte[4096];        
          int bytes_read;                
           
          // Read a chunk of bytes into the buffer, then write them out,
          // looping until we reach the end of the file (when read() returns -1).
          // Note the combination of assignment and comparison in this while
          // loop.  This is a common I/O programming idiom.

          while((bytes_read = from.read(buffer)) != -1)
            to.write(buffer, 0, bytes_read);          
        }

        finally {

          if (from != null) try { from.close(); } catch (IOException e) { ; }
          if (to != null) try { to.close(); } catch (IOException e) { ; }
        }
      }

      /** A convenience method to throw an exception */
      private static void abort(String msg) throws IOException {
        throw new IOException(msg);
      }
    }

    2. File Search :
    http://www.experts-exchange.com/Q_20838884.html

    My adviced is you got to read the program and read it line by line to understand it. There are lots of resources
    on the internet the can also help you. Thanks for the time just dont forget to close this one.

    Hope that helps . . .
    Javatm
    0
     
    LVL 15

    Expert Comment

    by:Javatm
    Still There ???
    0
     

    Author Comment

    by:adidas7fire
    Yes, I'm still here... just trying to go through every line and figure out what each means and does, in respect to the code.  Thanks again for your help!
    0
     

    Author Comment

    by:adidas7fire
    What I am trying to do is write a class called Rectangle that maintains two attributes to represent the length and breadth of a rectangle. I've got to provide suitable get, set, and toString methods plus two methods that return the perimeter and area of the rectangle. Also, I must include two constructors for this class. One a parameterless constructor that initializes both the length and breadth to 0, and the second one that takes two parameters to initialize the length and breadth.  So far, this is what I have:


    import java.io.*;

    public class Rectangle
    {
      protected long length;
      protected long width;
          
    //....constructors go here

      public long get_length(){return length;}
      public long get_width(){return width;}
      public void set_length(long len){length = len;}
      public void set_width(long wid){width = wid;}
      public long area(){return width * length;}
      public long perimeter(){return 2 * (width + length);}
    }

    -----------------------------------------
    //2 Constructors

    public Rectangle()
       {
         length = 0;
         width = 0;
       }
          
      public Rectangle(long len, long wid)
       {
         length = len;
         width = wid;
       }
    ------------------------------------------
    Then, after this, I've got to write a program (a driver application) that tests the above class by providing the users with the following menu options:
    1 - to set the length
    2 - to set the breadth
    3 - to get the length
    4 - to get the breadth
    5 - to get the perimeter
    6 - to get the area
    7 - to print the object as string
    0 - to quit
     
    Eventually,  this program should create one Rectangle object at the beginning using the default constructor, and then repeatedly call the appropriate method for that object depending on the user selection from the above menu.

    I'm not sure where to implement the code for this information or what I am missing.  Could you help me out please?  Thanks in advance!
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Suggested Solutions

    Title # Comments Views Activity
    sumHeights2  challenge 7 29
    Receive file in Servlet 1 15
    bunnyEars2 challenge 6 28
    sumDigits  challenge 7 22
    Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
    Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

    884 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now