In Java I want to create a file from and save the data on it. The File
name with path is taken from user. Now if user give invalid path like C:\temp\./user\fir/st.csv
which is an invalid path because "."
and /
are in the path and on windows operating system "\"
is used as path separator.
Before executing the program(a command line tool), there was no temp
folder in C:\
directory, but when I run the program it creates temp
folder then in temp
it creates user
then in user
it create fir
folder and finally st.csv
in it. While I want that if such type of invalid path or file name is given by the user user should be noticed by message "Invalid path or file name"
.
What should I do? Program code is like below:
public class FileTest {
public static void main(String args[]) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter path:");
String path = br.readLine();
File file = new File(path);
String path1 = file.getParent();
File file2 = new File(path1);
if (!file2.exists()) {
System.out.println("Directory does not exist , So creating directory");
file2.mkdirs();
}
if (!file2.exists()) {
System.out.println("Directory can not be created");
} else {
FileWriter writer = new FileWriter(file);
PrintWriter out = new PrintWriter(writer);
System.out.println("Please enter text to write on the file, print exit at new line to if finished");
String line = "";
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("exit")) {
System.out.println("Thanks for using our system");
System.exit(0);
} else {
out.println(line);
out.flush();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Now if I give the path as C:\tump\./user\fir/st.csv
then it create tump
folder in C
drive , then user in tump
, then fir
in user
folder then st.csv
file in it.