2016-08-01 74 views
0

main類它接受用戶輸入作爲文件名。使用構造函數創建一個文本文件並獲取用戶輸入的文件名

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非常新,所以對此很有幫助。

+0

相關:http://stackoverflow.com/questions/579445/java-constructors – 0aslam0

+0

請詳細說明你的問題。你不是已經在'File newFileName = new File(userInputFileName);'中使用構造函數嗎?沒有理解你的問題。 –

+0

我想要使用java編碼標準來做到這一點,我需要在不同的類或包中創建構造函數。這是怎麼做到的? –

回答

-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) 
} 
相關問題