MATLAB: GUI to select a file if it exists else create a new one

MATLABmatlab gui

Hi,
As part of my application, I need a GUI-based approach to select a file. It should basically allow the user to select a file, if it exists (return full file path similar to uigetfile) else return the fullpath of the filename entered manually in the file selection dialog (similar to uiputfile). All my application needs is a filepath for its operation.
I have tried uigetfile() but it throws an error if the filename entered does not exist. I tried putting it in try.. catch.. construct but I believe the error is handled internally in uigetfile. If I use uiputfile(), when an existing file is selected, it asks whether the file should be replaced.
I was wondering if there is a setting in either of these built-in functions to achieve what I'm trying to do.
If possible, I'd like to avoid generating a custom UI for something as simple as this.
Any pointers would be really appreciated.
Cheers,
sunny

Best Answer

Hi Sunny,
[fileName,pathName,index] = uiputfile({'*.xlsx';'*.xls'},'Please Select a file Location','My Default File Name.xlsx');
if index % if user selects a target location for his/her file no matter if it is a new file name(which does not exist) or existing file name index will be 1.
fullfilePath = fullfile(pathName,fileName)
else % if user presses cancel and does not select anything, index will be 0.
return % user didn't select so return
end
The natural behaviour of the replacement file is Window's behaviour. So if a file already exists, it will always ask for replacement.
You can also do that:
  1. Ask for a file name with inputdlg function from user
  2. Ask for a folder path name with uigetdir (it only allows selecting folder not a file) from user.
  3. Combine pathName and fileName from those 2 inputs from user with fullfile function and continue working on it.
The third method you can apply is a java hack directly gets you the full file name with path:
parframe = com.mathworks.hg.peer.utils.DialogUtilities.createParentWindow;
obj = javahandle_withcallbacks.com.mathworks.mwswing.MJFileChooser;
obj.showOpenDialog(parframe);
filename = char(obj.getSelectedFile);
Note that if user selects an existing file, and you are going to save something on that full file name, it will definetely overwrite the existing file.