0

main Class Which is accepting user input as a file name.

public class Main {

    public static void main(String args[]) throws Exception{
        FileOperator fileObject = new FileOperator();
        System.out.println(Strings.userMenu);
        @SuppressWarnings("resource")
        Scanner scan= new Scanner(System.in);
        String userInput = scan.next();
        if(userInput.isEmpty()){
            System.out.println(Strings.inputExpected);
        }
        else{           
            fileObject.fileOperator(userInput);
        }

    }
}

/* It is a generic file which takes user input as a file name and saves the file with that name.*/

public class FileOperator {

/*
 * The Below Method fileOperator will access filename as a input from user.
 * Checks if the file is available in given path.
 * If File is available then file exist message will be printed.
 * Else new file with that name will b created.
 * If user enters nothing then error message will be popped up.
 */

    public  void fileOperator(String userInputFileName) throws Exception { 

            File newFileName = new File(userInputFileName);

        if(newFileName.exists() && !newFileName.isDirectory()) { 
            System.out.println(Strings.fileExists);
        }
        else if (newFileName.createNewFile()){
                System.out.println(Strings.fileCreated);
              }
        else if(newFileName.equals("")){
            System.out.println("");
        }

        else{
                 System.out.println(Strings.errorForFileNotCreated);
            }
    }
}

But the problem is I want to create a file object using a constructor. I am very new to java so kindly help with this.

3
  • Related: stackoverflow.com/questions/579445/java-constructors Commented Aug 1, 2016 at 5:13
  • Please elaborate your question. Aren't you already using constructor in File newFileName = new File(userInputFileName); ? Didn't understood your question. Commented Aug 1, 2016 at 5:13
  • i want do this using java coding standards were i need to create constructors in different class or package. how is that done??? Commented Aug 1, 2016 at 5:15

1 Answer 1

0

Create constructor in FileOperator class:

public class FileOperator{
    public FileOperator(String filename){
          // here write fileOperator method code and delete that method
      }
}
in main delete FileOperator fileObject = new FileOperator(); // and write in else part 
{
  FileOperator fileObject = new FileOperator(userInput)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.