Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Copying a File

  1. #1
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Copying a File

    Hi guys it's my first time here, I hope you guys can help me out with my question.

    I'm to write a program that copies a file, I've already done that it works at copying but what I need help with is the professor wants to be able to do this from the command line:

    java FileCopy sourceFileName.txt to destinationFileName.txt

    How do i get my program to respond to such command from command prompt?
    This is my code it copies the file when it's run from Eclipse,

    Code:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    public class FileCopy
    {
    	String srcFileName;
    	String dstFileName;
    	String line;
    	BufferedReader source;
    	PrintWriter destination;
    	File fileSource;
    	File destinationFile;
    	
    	public FileCopy(String src, String dest)
    	{
    		this.srcFileName = src;
    		this.dstFileName = dest;
    		fileSource = new File(this.srcFileName);
    		destinationFile = new File(this.dstFileName);
    		try 
    		{
    			this.copyFile();
    		} 
    		catch (IOException e) 
    		{
    			e.printStackTrace();
    		}
    	}
    	
    	private boolean openFile()
    	{
    		try 
    		{
    			if (fileSource.exists())
    			{
    				source = new BufferedReader(new FileReader(fileSource));
    				return true;
    			}
    		}
    		catch (FileNotFoundException e) 
    		{
    			e.getMessage();
    		}
    		return false;
    	}
    	
    	private boolean copyFile() throws IOException
    	{
    		if (this.openFile() == true)
    		{
    			try 
    			{
    				destination = new PrintWriter(destinationFile);
    
    				do 
    				{
    					line = source.readLine();
    					if (line != null) 
    					{
    						destination.write(line + "\n");
    					}
    				}
    				
    				while (line != null);
    				source.close();
    				destination.close();
    				return true;
    			} 
    			catch (FileNotFoundException e) 
    			{
    				e.getMessage();
    			}
    		}
    		return false;
    	}
    	
    	public static void main (String[] args)
    	{
    		FileCopy newCopy = new FileCopy("sourceFile.txt", "destinationFile.txt");
    	}
    
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Easy peasy.
    In the main method the args represents what was passed to the main method. This is what is invoked with a command line call.
    In Java, you can get these under the args[0] and args[1] in your code. Quotations are removed so if you have a path with a space in it, you can safely wrap it with quotations during the command line call, and it will be without in the String[] provided to main.

  • #3
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    Easy peasy.
    In the main method the args represents what was passed to the main method. This is what is invoked with a command line call.
    In Java, you can get these under the args[0] and args[1] in your code. Quotations are removed so if you have a path with a space in it, you can safely wrap it with quotations during the command line call, and it will be without in the String[] provided to main.
    Thank you for your response, I was thinking it was something about that but when I insert any value into args[0-any number] and run the program it says outofboundsexception do you know why it would do that? Also how would I go about this can you provide an example please? would i just have

    public main void (String[] args)
    {
    Just 3 lines?
    }

  • #4
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    Easy peasy.
    In the main method the args represents what was passed to the main method. This is what is invoked with a command line call.
    In Java, you can get these under the args[0] and args[1] in your code. Quotations are removed so if you have a path with a space in it, you can safely wrap it with quotations during the command line call, and it will be without in the String[] provided to main.
    Thanks for the reply but I tried giving values to args[] and it will give me an outofboundsexception error Can you show me an example of something please so i can go about it by following the example, would i just leave my main class empty other than the args[]?

  • #5
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    The main method signature in Java is only a string array.
    To prevent out of bound exceptions, you can either try/catch them or simply verify the length first:
    PHP Code:
    public static void main(String[] argv)
    {
        if (
    argv.length != 2)
        {
            
    System.out.println("Incorrect command line call of application.");
        }
        else
        {
            
    String sOriginating argv[0];
            
    String sDestination argv[1];
            
    // copy stuff here.
        
    }


  • #6
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    The main method signature in Java is only a string array.
    To prevent out of bound exceptions, you can either try/catch them or simply verify the length first:
    PHP Code:
    public static void main(String[] argv)
    {
        if (
    argv.length != 2)
        {
            
    System.out.println("Incorrect command line call of application.");
        }
        else
        {
            
    String sOriginating argv[0];
            
    String sDestination argv[1];
            
    // copy stuff here.
        
    }

    I can't get this to work I'm getting pretty frustrated, in the main am i supposed to use the constructor to create a file because if i do my constructer is already copying a file.

    Do i do something like this:

    Code:
    FileCopy copier = new FileCopy(srcFileName, dstFileName);
    		if (args.length != 3)
    	    {
    	        System.out.println("Incorrect command line call of application.");
    	    }
    	    else
    	    {
    	    	String to = "to";
    	        srcFileName = args[0];
    	        to = args[1];
    	        dstFileName = args[2];
    	    }
    Sorry I've just never done anything with the command prompt no idea how to make it work

  • #7
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Nope, filecopy has to be constructed in the else after you extract the variables you need.

  • Users who have thanked Fou-Lu for this post:

    ubiByte (10-19-2012)

  • #8
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    Nope, filecopy has to be constructed in the else after you extract the variables you need.
    Okay I got it figured out it's working now, thanks so much for helping me out, you've been a great help.

  • #9
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Out of curiosity, how does one add exceptions to this? Would they be added to the copyFile method as additional catch phrases, i.e.

    Code:
    catch (ExceptionNameHere exec){
        exec.getMessage("message text");
    }
    Thanks in advance...

  • #10
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I see that doesn't work...Guess I need to figure that one out, and quick.

  • #11
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    I don't understand the question.
    Exception catching can be done anywhere which an exception can be thrown.

  • #12
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I think I figured it out per our instructions. I'll respond again if I need help... thanks for checking in!

  • #13
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I can get the file to copy, however, when testing specific conditions as outlined in the assignment, I'm not getting errors as I should. There is a method that outlines the handling of each specific instance, which I have below:

    Code:
    private void commandParser(String[] args){
    		if(args.length != 3){
    			try {
    				throw new CopyCommandPException();
    			} catch (CopyCommandPException e) {
    				e.printStackTrace();
    			}
    			
    			if(!this.srcFile.exists()){
    				System.out.println("File does not exit.");
    				try{
    					throw new FileNameException();
    				}catch (FileNameException e){
    					e.printStackTrace();
    				}
    					
    			}
    			
    			if(!this.srcFileName.endsWith(".txt")){
    				try{
    					throw new FileNameException();
    				}catch (FileNameException e){
    					e.printStackTrace();
    				}
    			}
    			
    			if(!this.dstFileName.endsWith(".txt")){
    				dstFileName.endsWith(".txt");
    				
    				try{
    					throw new FileNameException();
    				}catch (FileNameException e){
    					e.printStackTrace();
    				}
    			}
    			
    				if(srcFileName != "sourceFileName.txt" || dstFileName != "destinationFileName.txt"){
    					try{
    						throw new FileNameException();
    					}catch (FileNameException e){
    						e.printStackTrace();
    					}
    				}
    			
    				if(srcFileName == dstFileName){
    					System.out.println("The filenames cannot be the same.");
    					System.out.println("Change the destination name to sourceFileName-copy.txt? (y or n): ");
    					Scanner input = new Scanner(System.in);
    					String ans = input.next();
    						if(ans.equalsIgnoreCase("y")){
    							args[3] = "sourceFileName-copy.txt";
    						}else{
    										
    							try{
    								throw new DuplicatedFileNameException();
    								}catch (DuplicatedFileNameException e){
    									e.printStackTrace();
    							}
    						}
    					}
    				}
    		}
    The test conditions are:
    • java FileCopy sourceFileName.txt too destinationFileName.txt
    • java FileCopy sourceFileName.txt to destinationFileName
    • java FileCopy sourceFileName to destinationFileName.txt
    • java FileCopy sourceFileName.txt to sourceFileName.doc
    • java FileCopy source.txt to destinationFileName.txt
    • java FileCopy sourceFileName.txt to destinationFileName.txt

    obviously, when I type in the last, it copies the file. However, the others do not elicit any error messages as intended.

  • #14
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Apparently, I didn't pass the commandParser() method to args in the main. How do I do that??? (Sorry, I've been sitting at the PC for what feels like 3 days straight and I'm starting to burn out).

  • #15
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Doing this is completely pointless:
    Code:
    				try{
    					throw new FileNameException();
    				}catch (FileNameException e){
    					e.printStackTrace();
    				}
    This is simply manually triggering an exception and being caught in the same block. It serves no purpose. The only time you should bother throwing an exception within a try manually is if its to force the remaining code to not execute. That is easily done in an if branch though.

    Exceptions should be used for when you do not know if if a condition may be raised, but could possibly be raised. You can throw your own exceptions, but you should be handling them in the caller if this is the case. Exceptions are raised by a block of code since they don't know what else to do with them. They leave it up to whatever called the method to determine how to proceed.

    IMO every one of these conditions above are valid. The only possible exception is sourceFileName.txt to sourceFileName.doc, and that is still debatable. The extension itself means nothing on the data within the file, so I don't see an issue with that. I'm not sure why you have a condition like this: if(srcFileName != "sourceFileName.txt" || dstFileName != "destinationFileName.txt"). Don't forget the rules of strings as well; use .equals for comparisons of immutable types, not == and !=. But these rules overall say you must use suorceFileName.txt and destinationFileName.txt, so what is the point of having the arguments provide to the java command line?


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •