• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 572
  • Last Modified:

Copying and concatenating from one file to another

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
adidas7fire
Asked:
adidas7fire
  • 5
  • 3
1 Solution
 
JavatmCommented:
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
 
JavatmCommented:
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
 
JavatmCommented:
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
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
adidas7fireAuthor Commented:
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
 
JavatmCommented:
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
 
JavatmCommented:
Still There ???
0
 
adidas7fireAuthor Commented:
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
 
adidas7fireAuthor Commented:
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

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now