CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   Copying a File (http://www.codingforums.com/showthread.php?t=277930)

ubiByte 10-19-2012 03:50 PM

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");
        }

}


Fou-Lu 10-19-2012 03:56 PM

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.

ubiByte 10-19-2012 04:01 PM

Quote:

Originally Posted by Fou-Lu (Post 1282328)
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?
}

ubiByte 10-19-2012 04:10 PM

Quote:

Originally Posted by Fou-Lu (Post 1282328)
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[]?

Fou-Lu 10-19-2012 08:12 PM

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.
    
}



ubiByte 10-19-2012 09:08 PM

Quote:

Originally Posted by Fou-Lu (Post 1282504)
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

Fou-Lu 10-19-2012 11:44 PM

Nope, filecopy has to be constructed in the else after you extract the variables you need.

ubiByte 10-19-2012 11:52 PM

Quote:

Originally Posted by Fou-Lu (Post 1282584)
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.

OldBlue 10-26-2012 06:01 PM

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...

OldBlue 10-26-2012 06:37 PM

I see that doesn't work...Guess I need to figure that one out, and quick.

Fou-Lu 10-26-2012 06:53 PM

I don't understand the question.
Exception catching can be done anywhere which an exception can be thrown.

OldBlue 10-26-2012 08:20 PM

I think I figured it out per our instructions. I'll respond again if I need help... thanks for checking in!

OldBlue 10-26-2012 08:56 PM

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.

OldBlue 10-26-2012 09:13 PM

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).:(

Fou-Lu 10-26-2012 09:21 PM

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?


All times are GMT +1. The time now is 05:20 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.