Created
September 25, 2017 11:19
-
-
Save javamultiplex/93a42c6780a08ae28f902cf624039488 to your computer and use it in GitHub Desktop.
How to create new file in Java?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.filehandling; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.InputMismatchException; | |
import java.util.Scanner; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category File Handling | |
* @problem How to create new file? | |
* | |
*/ | |
public class CreateFile { | |
public static void main(String[] args) throws IOException { | |
Scanner input = null; | |
BufferedReader br = null; | |
try { | |
boolean result = false; | |
input = new Scanner(System.in); | |
br = new BufferedReader(new InputStreamReader(System.in)); | |
System.out.println("Enter drive letter : "); | |
char ch = input.next(".").charAt(0); | |
System.out.println("Enter file name with extension : "); | |
String fileName = br.readLine(); | |
if (isValidFileName(fileName)) { | |
result = createNewFile(ch, fileName); | |
if (result) { | |
System.out.println("File " + fileName + " successfully created in " + ch + " drive."); | |
} | |
} else { | |
System.out.println("Enter file name correctly!"); | |
} | |
} catch (InputMismatchException e) { | |
System.out.println("Enter drive letter correctly!"); | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
if (br != null) { | |
br.close(); | |
} | |
} | |
} | |
private static boolean createNewFile(char ch, String fileName) { | |
// Creating File reference. | |
File file = new File(ch + ":\\" + fileName); | |
boolean result = false; | |
// Checking whether file exist or not in given path. | |
if (file.exists()) { | |
System.out.println("File " + fileName + " already exist in " + ch + " drive."); | |
} else { | |
try { | |
result = file.createNewFile(); | |
} catch (IOException e) { | |
System.out.println("Error occured in creating new file.\n" + e.getMessage()); | |
} | |
} | |
return result; | |
} | |
private static boolean isValidFileName(String fileName) { | |
String pattern = "^.+\\..+$"; | |
boolean result = false; | |
if (fileName.matches(pattern)) { | |
result = true; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment