My task is to save a file in the path specified by the end user (must be an absolute path). Am currently facing three different scenarios as in below:
- Path name is invalid (cannot be created) - for ex, path name provided by user : sfg rgdf gfggdgfudf
- Path name is invalid (but, it can be created) - for ex : C:\Parent\Child\GrandChildren (here C:\Parent exists whereas Child\GrandChildren does not.
- Path name is valid (i.e. directory exists) - for ex : C:\Parent\Test
For the first case, I need to save the file in a default location. For the second, I need to create directories and save the file. And for the last, I'll save in the specified path.
Below is my code snippet which is saving the file in default location for both first and second scenarios. Am having difficulty to distinguish between first and second. java.io.File.mkdirs works for the second case, but not for the first. Please ignore my poor code as am new to this programming language. Any inputs would be much appreciated.
//User input must be absolute path
String saveToFolder = "kut igeiguye jh";
String defaultFolder = "C:\\Parent\\Data";
try{
File file = new File(saveToFolder);
if(!file.exists()){
saveToFolder = defaultFolder;
}
file.mkdirs();
}catch(Exception e){
saveToFolder = defaultFolder;
}
//code to save data in path **saveToFolder**