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
11 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
Risposta accettata
Luna
il 18 Mar 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Environment and Settings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!