building a panel in which choose where save file - java

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.

Related

How to Get selected folder name in java using JFileChooser?

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

How to get the file extension in JfileChooser if the user input the filename without extension

I used the JFileChooser in my app. My question is if the user typing file name without the file extension on the dialog box; the app will allow more another file extension. How can I get the file extension on the file as type drop down box. I used fileChooser.getSelectedFile().getName() or fileChooser.getSelectedFile().getAbsolutePath() didn't get the extension. Would someone help me how to do it.
There is my code:
#SuppressWarnings("static-access")
private String getSavedFileName()
{
String rtnValue="";
JFileChooser fileChooser = new JFileChooser();
String PDFEXTENSION= "pdf";
FileNameExtensionFilter pdfType=new FileNameExtensionFilter("PDF File (."+ PDFEXTENSION + ")", PDFEXTENSION);
fileChooser.addChoosableFileFilter(pdfType);
fileChooser.setFileFilter(pdfType);
//clear "All files" from dropdown filter box
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showSaveDialog(this.splitRightPane);
if (returnVal == fileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// String extension = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
String fileAbsolutePath=file.getName();
file.getAbsolutePath()
String extension =fileAbsolutePath.substring(fileAbsolutePath.lastIndexOf(".") + 1, fileAbsolutePath.length() );
if ( PDFEXTENSION.equalsIgnoreCase(extension)){
rtnValue=fileAbsolutePath;
} else{
Utility.DisplayWarningMsg("Only PDF File");
}
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
return rtnValue;
}

Open folder containing file and highlight it

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");
}
}

Best way of opening a file (and ensuring file is chosen)

I have two seperate methods of opening a file.
The first uses a FileChoser with an additional file type filter.
JFileChooser inFileName = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PCF & TXT Files", "pcf", "txt");
inFileName.setFileFilter(filter);
Component parent = null;
int returnVal = inFileName.showOpenDialog(parent);`
The second uses a JOptionPane but has a loop to ensure the directory chosen exists
String filePath;
File directory;
do{
filePath = JOptionPane.showInputDialog("please enter directory");
directory = new File(filePath);
if (directory.exists()==false){
JOptionPane.showMessageDialog(null,"error with directory");
}
}while(directory.exists()==false);
I'm looking to get the best of both here. To be able to choose a file, using a file filter and also loop that function should that directory not be valid.
I've tried switching around variable names and the various functions in different places but I cant seem to get the loop (".exists" function) to work.
You just need to modify your JFileChooser code to use a loop.
JFileChooser inFileName = new JFileChooser();
File file;
boolean valid = false;
while (!valid) {
int returnVal = inFileName.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = inFileName.getSelectedFile();
valid = file.isDirectory();
else {
valid = returnVal == JFileChooser.CANCEL_OPTION;
}
}
Its worth mentioning that this kind of thing might be better achieved using;
jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

Java ask for overwrite jfilechooser

I have a function that should get the path of a file typed in the textinput of a jfilechooser and pass it to a String. The problem is that I want to check for overwrite if the file exists already. I do have a clue about how to do this, my problem, though, is that, if answering no to the JOptionPane, the JFileChooser closes anyway, because the save button has already been actioned. Now, what I need is that if the answer is no, the program returns to the JFileChooser, still prompting for a name.
Please note that I am searching for an efficient solution, I've already considered executing the function again, but since my program is quite a large one, this way of solving things would cost time and would not be efficient.
Here is the code of my function, yet not completed because I don't know how to handle it.
`public String FileSavePath()throws NullPointerException
{
File f=null;
String theFilepath=null;
JFileChooser FileChooser = new JFileChooser();
if(FileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
theFilepath=FileChooser.getSelectedFile().getAbsolutePath();
f=FileChooser.getSelectedFile();
//System.out.println(theFile);
if(f.exists())
{
int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?",
"Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
if(result==JOptionPane.YES_OPTION)
{
return theFilepath;
}
else // here is what I should do if the user answers 'no' or cancels/closes the JOptionPane
}
else return null;
return theFilepath;
}`
You need to place your query into a loop until such time as the user can provide you with an acceptable response...
public String FileSavePath() throws NullPointerException {
boolean acceptable = false;
String theFilepath = null;
do {
theFilepath = null
File f = null;
JFileChooser FileChooser = new JFileChooser();
if (FileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
theFilepath = FileChooser.getSelectedFile().getAbsolutePath();
f = FileChooser.getSelectedFile();
//System.out.println(theFile);
if (f.exists()) {
int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?",
"Existing file", JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.YES_OPTION) {
acceptable = true;
}
} else {
acceptable = true;
}
} else {
acceptable = true;
}
} while (!acceptable);
return theFilepath;
}

Categories