有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用构造函数创建文本文件,并将用户输入作为文件名

接受用户输入作为文件名的主类

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

但问题是我想用构造函数创建一个文件对象。我对java非常陌生,所以请帮忙


共 (1) 个答案

  1. # 1 楼答案

    在FileOperator类中创建构造函数:

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