Vishal Sindagi Vishal Sindagi - 1 year ago 66
Java Question

use constructors to create a text file and take user input for filename

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();
Scanner scan= new Scanner(;
String 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()) {
else if (newFileName.createNewFile()){
else if(newFileName.equals("")){


But the Problem is that I want to create a file object using a constructor, m very new to java so kindly help with this. Thank You.

Lol Lol
Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download