I want to select the folder that is selected.
JFileChooser targetDir = new JFileChooser();
targetDir.setDialogTitle("Choose Target Directory.");
targetDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(targetDir.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
System.out.println(targetDir.getCurrentDirectory());
main_mw = new MainWindow("XYZ Copier");
main_mw.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
} else {
System.exit(0);
}
} else {
}
It gives the output "/home/rahul/Downloads/mc"
but I need "/home/rahul/Downloads/mc/lib". It gives same result if i go inside lib.
Screenshots:
JFileChooser#getSelectedFile will return the selected file/directory
getCurrentDirctory returns the directory which is currently been shown in the chooser
Related
I have next code:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNajitPDFCache) {
JFileChooser chooser;
String choosertitle = "Select directory.";
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText("OK");
//
// disable the "All files" option.
//
chooser.setAcceptAllFileFilterUsed(false);
//
if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
textFieldPDFCache.setText(chooser.getCurrentDirectory()+"");
}
}
}
That's Ok. I choose c:\test folder in opened chooser form and next I click on button OK.
But chooser.getCurrentDirectory() return only c:\ . Why? What is wrong?
getCurrentDirectory() returns the current directory that is opened in the
JFileChooser. When you are selecting C:\test you opened C:\ directory, so you are getting C:\ on getCurrentDirectory()
The getSelectedFile() returns the file that is selected (in your case the file is a directory). So you if you want the directory that is selected by the user use getSelectedFile()
You should use chooser.getSelectedFile() instead.
You Can Set Canonical path as
File Canonicalpath = new File(new File("C:/").getCanonicalPath());
I'm needing to open a folder containing the specified file, and highlight this said file. I have been looking for this for long but I have been unlucky. Could someone explain how this could be done using java?
Would be much appreciated. I am able to open files, folders, but not open the containing folder and highlighting a file. Cross platform code would be a plus, or just point me to the direction! Thanks!
#UPDATE:
Basically I'm doing an image sorter. I have a ArrayList containing filenames, e.g. myarraylist.get(0) would return funny_cat.jpg
This can be a handy functionality to have in a program that works with files/folders. It's easy enough to actually open the containing folder using:
I want the user to be able to open the currently selected item in a JList and open the containing folder with the target file selected.
I would post the code but it is too long and most unnecesary for this question, I will however post below how I open an explorer window, for the settings section of program, in order to choose a new directory to use:
public void browseFolder(){
System.out.println("browsing!");
final JFileChooser fc = new JFileChooser();
File dir = new File(core.Loader.path);
fc.setCurrentDirectory(dir);
// Windows and Mac OSX compatibility code
if (System.getProperty("os.name").startsWith("Mac OS X")) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
}
fc.setApproveButtonText("Choose directory");
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
// if the user accidently click a file, then select the parent directory.
if (!f.isDirectory()) {
f = f.getParentFile();
}
// debug
System.out.println("Selected directory for import " + f);
}
}
#UPDATE
I have found the solution, will post as answer below.
So, I just called this method from the action performed and it does the trick.
Basically, the solution was to make this terminal command:
open -R absolute/path/to/file.jpg
This is for Mac OS X only, below is my method I use:
public void openFileInFolder(String filename){
try {
Process ls_proc;
String mvnClean = "open -R " + core.Loader.path + "/" + file_chosen;
String OS = System.getProperty("os.name");
System.out.println("OS is: " + OS);
if (OS.contains("Windows")) {
//code ...
} else {
ls_proc = Runtime.getRuntime().exec(mvnClean);
}
} catch (Exception e){
System.err.println("exception");
}
}
can the users select one or more than one mp3 files using JFileChooser?
I can only select user one file , using this method.
Just set the multi-selection to true and the selection mode to JFileChooser.FILES_AND_DIRECTORIES and it will work for a multiple files and all the files in a directory:
fileChooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
fileChooser.setMultiSelectionEnabled(true);
Then retrieve all the files this way:
fileChooser.getSelectedFiles();
My understanding of your requirement is:
User can choose one or multiple files
If a single file is chosen, then you work with that file
If multiple files are chosen then you would create a playlist and work with this playlist.
If this is what you want, I think the following might work for this scenario. Note that I've left the implementation to you because you know how to create a playlist or how to create a single file and feed it to your player.
/** This method returns a set of files chosen by the user.
* Returns null if selection is cancelled
**/
private File[] openFiles(){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
int optionChosen = fileChooser.showOpenDialog(this);
return (optionChosen == JFileChooser.CANCEL_OPTION) ? null : fileChooser.getSelectedFiles();
}
public void actionPerformed(ActionEvent e){
File[] selectedFiles = openFiles();
if(selectedFiles == null){
//handleNoFileChosen
}else if(selectedFiles.length == 1){
//handle single file selected
}else{
//handle creating playlist
}
}
I would build a panel which let me choose where I can save a file. I read java documentation and I saw that there is a swing component named file chooser but I don't know how use it.what i want to do is choose the path in my machine where saved a file created.
How to use it? Well, you just need to "use it"! Really!
This will create your FileChooser instance and set it to start at user's desktop folder:
JFileChooser fc = new JFileChooser(System.getProperty("user.home") + "/Desktop");
After that, you can set a variety of options. In this case, i'm setting it up to allow choosing multiple files, and only ".xls" (Excel) files:
fc.setMultiSelectionEnabled(true);
SelectionEnabled(true);
FileFilter ff = new FileFilter() {
#Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = f.getName().substring(f.getName().lastIndexOf("."));
if (extension != null) {
if (extension.equalsIgnoreCase(".xls")) {
return true;
} else {
return false;
}
}
return false;
}
#Override
public String getDescription() {
return "Arquivos Excel (\'.xls\')";
}
};
fc.setFileFilter(ff);
And finally, i'm showing it up and getting the user's choice and chosen files:
File[] chosenFiles;
int choice = fc.showOpenDialog(fc);
if (choice == JFileChooser.APPROVE_OPTION) {
chosenFiles = fc.getSelectedFiles();
} else {
//User canceled. Do whatever is appropriate in this case.
}
Enjoy! And good luck!
This tutorial, straight from the Oracle website, is a great place to start learning about FileChoosers.
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + ".");
} else {
log.append("Open command cancelled by user.");
}
The above code opens a FileChooser, and stores the selected file in the fc variable. The selected button (OK, Cancel, etc) is stored in returnVal. You can then do whatever you wish with the file.
I have a program that takes a screenshot of my gui. It automatically saves the .gif file to the eclipse project directory. What I would like is to have it asking a user where to save the image. Basically so the user can browse the file directory and choose the directory.
Here's the code I have:
public void actionPerformed(ActionEvent event) {
try{
String fileName = JOptionPane.showInputDialog(null, "Save file",
null, 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Error: file name must end with \".gif\".",
null, 1);
}
else{
BufferedImage image = new BufferedImage(panel2.getSize().width,
panel2.getSize().height, BufferedImage.TYPE_INT_RGB);
panel2.paint(image.createGraphics());
ImageIO.write(image, "gif", new File(fileName));
JOptionPane.showMessageDialog(null, "Screen captured successfully.",
null, 1);
}
}
catch(Exception e){}
I would use a file chooser dialog instead of a JOptionPane. Here is a link for the tutorial.
Example:
First of all you have to declare JFileChooser object in your class and initialize it.
public Class FileChooserExample{
JFileChooser fc;
FileChooserExample(...){
fc = new JFileChooser();// as a parameter you can put path to initial directory to open
...
}
Now create another method:
private String getWhereToSave(){
int retVal = fc.showSaveDialog(..);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
return file.getAbsolutePath();
}
return null;
}
This method returns to you the absolute path which user selected. retVal indicates which button was pressed (Save or Cancel). And if it was pressed Save then you handle the selected file.
Then you have this method you can incorporate this with your code. Instead of this line:
String fileName = JOptionPane.showInputDialog(null, "Save file", null, 1);
Write:
String fileName = getWhereToSave();