Choose a file
Solved
Vitaldix
Posted messages
116
Registration date
Status
Membre
Last intervention
-
Vitaldix Posted messages 116 Registration date Status Membre Last intervention -
Vitaldix Posted messages 116 Registration date Status Membre Last intervention -
Hello!
So here is my little problem! I would like my program to ask the user to choose a file; the user can choose any file they want, and the program retrieves the content of that file.
I have this:
which works wonderfully but of course it only works for the file located in that spot.
I also found this:
There I can indeed navigate through my directories and select any file I want, but nothing happens! I feel like I can't retrieve my file!
I tried to tinker with things, mixing these two pieces of code together, but nothing works; can you help me out?
Thanks!
So here is my little problem! I would like my program to ask the user to choose a file; the user can choose any file they want, and the program retrieves the content of that file.
I have this:
File file = new File("file_location"); Scanner sc = new Scanner(file); which works wonderfully but of course it only works for the file located in that spot.
I also found this:
FileSystemView systemView = FileSystemView.getFileSystemView(); //retrieving directories File defaultDir = systemView.getDefaultDirectory(); File home = systemView.getHomeDirectory(); //creating and displaying JFileChooser JFileChooser defaultChooser = new JFileChooser(defaultDir); defaultChooser.showOpenDialog(null); JFileChooser homeChooser = new JFileChooser(home); homeChooser.showOpenDialog(null);
There I can indeed navigate through my directories and select any file I want, but nothing happens! I feel like I can't retrieve my file!
I tried to tinker with things, mixing these two pieces of code together, but nothing works; can you help me out?
Thanks!
1 réponse
JFileChoosers only allow the selection of one (or multiple) files (and/or directories) for reading (or writing), but once the files are chosen, it's up to you to process them.
See: How to Use File Choosers
--
Trust does not exclude control
See: How to Use File Choosers
JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if (chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) { File[] files = chooser.getSelectedFiles(); ... } --
Trust does not exclude control
doesn't work.
It contains all the selected files, so you need to process the files one by one with your Scanner.
File[] files = chooser.getSelectedFiles(); for (File file : files) { Scanner sc = new Scanner(file); ... sc.close(); }chooser.setMultiSelectionEnabled(false); if (chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); Scanner sc = new Scanner(file); ... sc.close(); }However, I have an issue with the execution of the program, now I have
do you know where it comes from?