I want to get the full path of the file that the user saved in Java.
Here is the code of the method save and it works okay but actually i need to get the path that the user had save his file in. Could someone help me:
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class FileChooserSave {
private static void createAndShowUI() {
final JFileChooser chooser = new JFileChooser(new File(".")) {
public void approveSelection() {
if (getSelectedFile().exists()) {
int n = JOptionPane.showConfirmDialog(this, "Do You Want to Overwrite File?", "Confirm Overwrite",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION)
super.approveSelection();
} else
super.approveSelection();
}
};
chooser.setSelectedFile(new File(""));
int returnVal = chooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println(chooser.getSelectedFile());
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Here is a sample of java code for absolute path from JFileChoose
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
hope it helps...
You can get the Absolute path using this method:
myFileChooser.getSelectedFile().getAbsolutePath()
Related
I've been trying to use JFileChooser but I have the problem that the program doesn't stop running, here's my code:
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class copiarArcivos {
public static void main(String[] args) {
JFileChooser();
}
public static void JFileChooser(){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(new JFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
}
}
Should I simply put a break at the end of the if?
Don't create an empty JFrame. You can just use null:
//int result = fileChooser.showOpenDialog(new JFrame());
int result = fileChooser.showOpenDialog(null);
You have to change the method name of JFileChooser in main method. and also in the declaration of this method. You can use JFileChooser2 instid of JFileChooser on both.
I am using JFileChooser to select a file and I am trying to limit the display to show only jpg or jpeg files. I have tried FileFilter and ChoosableFileFilter and it is not limiting the file selection. Here is my code:
JFileChooser chooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("JPEG file", new String[] {"jpg", "jpeg"});
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
debug.put("You chose to open this file: " + chooser.getSelectedFile().getAbsolutePath());
File selectedFile = new File(chooser.getSelectedFile().getAbsolutePath());
...
Try this:
import javax.swing.JFileChooser;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileFilter() {
public String getDescription() {
return "JPG Images (*.jpg)";
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
String filename = f.getName().toLowerCase();
return filename.endsWith(".jpg") || filename.endsWith(".jpeg") ;
}
}
});
Do you mean "it's not limiting the selection" as in "it's allowing the option for any file type"? If so, then try JFileChooser.setAcceptAllFileFilterUsed(boolean).
chooser.setAcceptAllFileFilterUsed(false);
According to the JFileChooser documentation, it should tell it not to add the all-file-types file filter to the file filter list.
Try and use fileChooser.setFileFilter(filter) instead of fileChooser.addChoosableFileFilter(filter).
Try to use fileChooser.setFileFilter(filter) after fileChooser.addChoosableFileFilter(filter), because you need to add your filter to fileChooser and then setting it as default value.
Here is the link with good example:
http://www.java2s.com/Code/Java/Swing-JFC/CustomizingaJFileChooser.htm
Here is a sample code!
private void btnChangeFileActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new ArffFilter());
int returnVal = fc.showOpenDialog(this);
...
}
Then
class ArffFilter extends FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
if (fileName.substring(i + 1).toLowerCase().equals("arff")) {
return true;
}
}
return false;
}
#Override
public String getDescription() {
return ".arff (Weka format)";
}
}
How could i delete a file in JFileChooser? I know that the AWT since being written in native could has an option to delete a file from it using the simple Delete button.
But what if i would like to delete the file in JFileChooser? When i am trying to delete, it i got an exception that the File is being accessed by another program and hence could not be deleted.
Two questions that i would like to ask in this situation are..
Questions
Is there any hack to delete a file through JFileChooser?
Why i am not getting File is being accessed by another program when i am deleting in FileDialog. Is it because it is written in native code?
Any help is appreciated. Thanks in advance.
Yeah! I got it! I even updated the JFileChooser after the file was deleted.
Updated
Added functionality to delete multiple files and modified jf.getUI().rescanCurrentDirectory(jf) to jf.rescanCurrentDirectory() and removed superfluous PropertyChangeListener as per sir Rob Camick's suggestion.
/*
* #see http://stackoverflow.com/a/17622050/2534090
* #author Gowtham Gutha
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
class DeleteThroughJFileChooser extends JFrame
{
JButton jb;
JFileChooser jf;
File[] selectedFiles;
public DeleteThroughJFileChooser()
{
// Create and show GUI
createAndShowGUI();
}
private void createAndShowGUI()
{
// Set frame properties
setTitle("Delete through JFileChooser");
setLayout(new FlowLayout());
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create JFileChooser
jf=new JFileChooser();
// Allow multiple selection
jf.setMultiSelectionEnabled(true);
// Create JButton
jb=new JButton("Open JFileChooser");
// Add ActionListener to it
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
// Show the file chooser
showFileChooser();
}
});
// Register the delete action
registerDelAction();
// Add JButton jb to JFrame
add(jb);
}
private void showFileChooser()
{
// Show the open dialog
int op=jf.showOpenDialog(this);
}
private void registerDelAction()
{
// Create AbstractAction
// It is an implementation of javax.swing.Action
AbstractAction a=new AbstractAction(){
// Write the handler
public void actionPerformed(ActionEvent ae)
{
JFileChooser jf=(JFileChooser)ae.getSource();
try
{
// Get the selected files
selectedFiles=jf.getSelectedFiles();
// If some file is selected
if(selectedFiles!=null)
{
// If user confirms to delete
if(askConfirm()==JOptionPane.YES_OPTION)
{
// Call Files.delete(), if any problem occurs
// the exception can be printed, it can be
// analysed
for(File f:selectedFiles)
java.nio.file.Files.delete(f.toPath());
// Rescan the directory after deletion
jf.rescanCurrentDirectory();
}
}
}catch(Exception e){
System.out.println(e);
}
}
};
// Get action map and map, "delAction" with a
jf.getActionMap().put("delAction",a);
// Get input map when jf is in focused window and put a keystroke DELETE
// associate the key stroke (DELETE) (here) with "delAction"
jf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"),"delAction");
}
public int askConfirm()
{
// Ask the user whether he/she wants to confirm deleting
// Return the option chosen by the user either YES/NO
return JOptionPane.showConfirmDialog(this,"Are you sure want to delete this file?","Confirm",JOptionPane.YES_NO_OPTION);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new DeleteThroughJFileChooser();
}
});
}
}
Why would you delete a file from the chooser?
Use the jfilechooser to get the name of the file and location store as a variable. Close the file jfilechooser. Then delete the file.
import java.io.File;
public class DeleteFileExample
{
public static void main(String[] args)
{
try{
File file = new File("c:\\logfile20100131.log");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Also, I found this code that might prove to be usefull if you want the functionality to be in the jfilechooser itself. From Here. To run this you will also need This. Swing file
import darrylbu.util.SwingUtils;
import java.awt.Container;
import java.awt.Point;
import java.awt.event.*;
import javax.swing.*;
public class FileChooserDeleteMenu {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FileChooserDeleteMenu().makeUI();
}
});
}
public void makeUI() {
final JFileChooser chooser = new JFileChooser();
final JList list = SwingUtils.getDescendantOfType(JList.class, chooser, "Enabled", true);
JPopupMenu popup = list.getComponentPopupMenu();
JMenuItem item = new JMenuItem("Delete");
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (chooser.getSelectedFile() != null) {
JOptionPane.showConfirmDialog(chooser,
"Delete " + chooser.getSelectedFile().getAbsolutePath() + "?",
"Confirm delete",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
}
}
});
popup.add(item);
final MouseListener listener = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if (e.getSource() == list) {
list.setSelectedIndex(list.locationToIndex(p));
} else {
JTable table = (JTable) e.getSource();
if (table.columnAtPoint(p) == 0) {
int row = table.rowAtPoint(p);
table.getSelectionModel().setSelectionInterval(row, row);
}
}
}
};
list.addMouseListener(listener);
final Container filePane = SwingUtilities.getAncestorOfClass(sun.swing.FilePane.class, list);
filePane.addContainerListener(new ContainerAdapter() {
#Override
public void componentAdded(ContainerEvent e) {
JTable table = SwingUtils.getDescendantOfType(JTable.class, chooser, "Enabled", true);
if (table != null) {
for (MouseListener l : table.getMouseListeners()) {
if (l == listener) {
return;
}
}
table.addMouseListener(listener);
}
}
});
chooser.showOpenDialog(null);
System.exit(0);
}
}
This is how to add a delete key listener to your JFileChooser:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.nio.file.Files;
public class JFileChooserUtilities
{
public static void registerDeleteAction(JFileChooser fileChooser)
{
AbstractAction abstractAction = new AbstractAction()
{
public void actionPerformed(ActionEvent actionEvent)
{
JFileChooser jFileChooser = (JFileChooser) actionEvent.getSource();
try
{
File selectedFile = jFileChooser.getSelectedFile();
if (selectedFile != null)
{
int selectedAnswer = JOptionPane.showConfirmDialog(null, "Are you sure want to permanently delete this file?", "Confirm", JOptionPane.YES_NO_OPTION);
if (selectedAnswer == JOptionPane.YES_OPTION)
{
Files.delete(selectedFile.toPath());
jFileChooser.rescanCurrentDirectory();
}
}
} catch (Exception exception)
{
exception.printStackTrace();
}
}
};
fileChooser.getActionMap().put("delAction", abstractAction);
fileChooser.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"), "delAction");
}
}
Code adapted from JavaTechnical's answer.
I have a JFileChooser that is created as shown:
JFileChooser chooser = new JFileChooser();
int choosen = chooser.showOpenDialog(fileSelector.this);
if (choosen == JFileChooser.CANCEL_OPTION) {
System.out.println("Closed");
}
If I close the window with out making a selection I get the error:
Exception in thread "main" java.lang.NullPointerException
at fileSelector.fileSelector(fileSelector.java:32)
at createAndControl.main(createAndControl.java:15)
I wanted to know what the proper way to handle this was, what action should I call on window closed to avoid this?
TIA
It's recommended to do it the other way round:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("Opening: " + file.getName() + ".\n");
} else {
System.out.println("Open command cancelled by user.\n");
}
}
});
}
I disable the new Folder button using the following code:
public void disableNewFolderButton( Container c ) {
System.out.print("in disable fn");
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton)comp;
Icon icon = b.getIcon();
if (icon != null
&& icon == UIManager.getIcon("FileChooser.newFolderIcon"))
{
System.out.print("in disable fn");
b.setEnabled(false);
}
}
else if (comp instanceof Container) {
disableNewFolderButton((Container)comp);
}
}
}
The code is called in the following lines:
JFileChooser of=new JFileChooser();
of.setAcceptAllFileFilterUsed(false);
of.addChoosableFileFilter(new MyFilter());
disableNewFolderButton(of);
But the new folder button is disabled only when the file chooser is first displayed. Suppose i go to some drive , say g: , then the button is enabled again. How to set this right?
this is working for me...
//Create a file chooser
UIManager.put("FileChooser.readOnly", Boolean.TRUE);
JFileChooser fc = new JFileChooser();
Disable the "new folder" Action (which in turn will disable the button):
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class FileChooserAction
{
public static void createAndShowUI()
{
JFileChooser chooser = new JFileChooser();
BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI();
Action folder = ui.getNewFolderAction();
folder.setEnabled(false);
chooser.showSaveDialog(null);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
1) It is a bit stupid, but you can keep disabling it in an another Thread. Until the file chooser got invisible.
2) Does hiding the button work? b.setVisible(false);