I know uiputfile() does not actually overwrite the file. However, the dialog box asking the user to confirm replacing the existing file can cause confusion.
GUI to select a file if it exists else create a new one
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Sunny Talekar
am 18 Mär. 2019
Kommentiert: Luna
am 20 Mär. 2019
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
Akzeptierte Antwort
Luna
am 18 Mär. 2019
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:
- Ask for a file name with inputdlg function from user
- Ask for a folder path name with uigetdir (it only allows selecting folder not a file) from user.
- 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.
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Schedule Model Components finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!