Skip to main content

Java Program to create an new File

import java.io.*;
import java.util.*;
import java.awt.*;
public class CreateFile {
 Scanner scan=new Scanner(System.in);
 String fileName;
 char ch;
 BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
 public void input(){
     try{
         System.out.printf("File Name: ");
         fileName=scan.nextLine();
     }
         catch(InputMismatchException e){
             System.err.println("Error Occured!\n"+e.getMessage());
         System.exit(0);
         }          
 }
 public void compute(){
     try{
      String path=getDesktopPath();
     File file=new File(path+"\\"+fileName+".txt");
     file.createNewFile();
     editFile(file);
 }
     catch(IOException e){
         System.err.println("Error Occured!\n"+e.getMessage());
         System.exit(0);
     }
 }
  public String getDesktopPath(){
        String path=System.getProperty("user.home")+"/Desktop";
        path=path.replace("\\", "/");
        return path;
    }
  public void editFile(File file){
      try{
       Desktop desktop=Desktop.getDesktop();
     if(desktop.isDesktopSupported()){
         System.out.println("Now you can edit you File!");
               desktop.getDesktop().edit(file);
     }
     else{
         System.err.println("Desktop not supports editing!");
         System.exit(0);
     }
      }
      catch(IOException e){
          System.err.println("Error Occured!\n"+e.getMessage());
          System.exit(0);
      }
  }
public static void main(String[] args){
    CreateFile obj=new CreateFile();
    obj.input();
    obj.compute();
}
}

Comments