Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Copying and concatenating from one file to another

Posted on 2004-10-30
8
Medium Priority
?
569 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
Comment
Question by:adidas7fire
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 15

Accepted Solution

by:
Javatm earned 2000 total points
ID: 12455155
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
ID: 12455183
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
ID: 12455199
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:adidas7fire
ID: 12455281
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
ID: 12456061
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
ID: 12477987
Still There ???
0
 

Author Comment

by:adidas7fire
ID: 12493702
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
ID: 12595970
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

Tech or Treat! - Giveaway

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

636 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