-
Notifications
You must be signed in to change notification settings - Fork 0
/
CreateFileInDirectory.java
89 lines (77 loc) · 2.33 KB
/
CreateFileInDirectory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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;
public class CreateFileInDirectory {
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 directory name : ");
String directoryName = br.readLine();
System.out.println("Enter file name with extension : ");
String fileName = br.readLine();
if (isValidFileName(fileName)) {
result = createNewFile(ch, directoryName, fileName);
if (result) {
System.out.println("File " + fileName
+ " successfully created in directory " + ch
+ ":\\" + directoryName);
}
} 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 directoryName,
String fileName) {
// Creating File reference.
File directory = new File(ch + ":\\" + directoryName);
// If directory doesn't exist then creating a new directory.
if (!directory.exists()) {
directory.mkdir();
}
// Creating File reference.
File file = new File(directory, fileName);
boolean result = false;
// Checking whether file exist or not in given path.
if (file.exists()) {
System.out.println("File " + fileName
+ " already exist in directory " + ch + ":\\"
+ directoryName);
} 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;
}
}