Java Program to create an File and if exists then the user will have the choice to Replace that File or not
import java.io.*;
import java.util.*;
import system.*;
public class ReplaceFiles{
Scanner scan=new Scanner(System.in);
String fileName;
char ch;
public void input(){
try{
System.out.printf("Enter File Name: ");
fileName=scan.nextLine();
ReplaceFiles();
}
catch(InputMismatchException e){
System.err.println("Error Occured!\n"+e.getMessage());
System.exit(0);
}
}
public void ReplaceFiles(){
try{
DesktopPath path=new DesktopPath();
String desktop="";
desktop=path.getDesktopAccutualPath();
File file=new File(desktop+"\\"+fileName+".txt");
if(!file.exists())
file.createNewFile();
else{
System.out.printf("File already exists!\nDo you want to replace it Y/N? ");
fileName=scan.next();
ch=fileName.charAt(0);
if(ch=='Y' || ch=='y')
file.createNewFile();
else if(ch=='N' || ch=='n'){
System.out.println("File not Replaced!");
System.exit(0);
}
else{
System.err.println("Illegal Character Used!");
System.exit(0);
}
}
if(file.exists()){
System.out.println("Enter you text and save it!");
Process run=Runtime.getRuntime().exec("notepad.exe "+file);
}
else
System.err.println("File not created!");
System.exit(0);
}
catch(IOException e){
System.err.println("Error Occured!\n"+e.getMessage());
System.exit(0);
}
}
public static void main(String[] args){
ReplaceFiles obj=new ReplaceFiles();
obj.input();
}
}
import java.util.*;
import system.*;
public class ReplaceFiles{
Scanner scan=new Scanner(System.in);
String fileName;
char ch;
public void input(){
try{
System.out.printf("Enter File Name: ");
fileName=scan.nextLine();
ReplaceFiles();
}
catch(InputMismatchException e){
System.err.println("Error Occured!\n"+e.getMessage());
System.exit(0);
}
}
public void ReplaceFiles(){
try{
DesktopPath path=new DesktopPath();
String desktop="";
desktop=path.getDesktopAccutualPath();
File file=new File(desktop+"\\"+fileName+".txt");
if(!file.exists())
file.createNewFile();
else{
System.out.printf("File already exists!\nDo you want to replace it Y/N? ");
fileName=scan.next();
ch=fileName.charAt(0);
if(ch=='Y' || ch=='y')
file.createNewFile();
else if(ch=='N' || ch=='n'){
System.out.println("File not Replaced!");
System.exit(0);
}
else{
System.err.println("Illegal Character Used!");
System.exit(0);
}
}
if(file.exists()){
System.out.println("Enter you text and save it!");
Process run=Runtime.getRuntime().exec("notepad.exe "+file);
}
else
System.err.println("File not created!");
System.exit(0);
}
catch(IOException e){
System.err.println("Error Occured!\n"+e.getMessage());
System.exit(0);
}
}
public static void main(String[] args){
ReplaceFiles obj=new ReplaceFiles();
obj.input();
}
}
Comments