如何通过JFileChooser删除文件?

时间:2013-07-12 17:58:28

标签: java swing jfilechooser

如何删除JFileChooser中的文件?我知道自用本机编写以来,AWT可以选择使用简单的Delete按钮从中删除文件。

但如果我想删除JFileChooser中的文件怎么办?当我试图删除时,我得到一个例外,文件被另一个程序访问,因此无法删除

我想在这种情况下提出的两个问题是..

问题

  1. 是否有 hack 通过JFileChooser删除文件?
  2. 当我在FileDialog中删除时,为什么我没有收到其他程序正在访问文件。是因为它是用本机代码编写的吗?
  3. 感谢任何帮助。提前谢谢。

3 个答案:

答案 0 :(得分:2)

呀!我知道了!我甚至在删除文件后更新了JFileChooser

已更新

添加了删除多个文件的功能,并修改了jf.getUI().rescanCurrentDirectory(jf)jf.rescanCurrentDirectory(),并根据Rob Camick的建议删除了多余的PropertyChangeListener

/*
* @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();
            }
        });
    }
}

答案 1 :(得分:0)

为什么要从选择器中删除文件?

使用jfilechooser将文件名和位置存储作为变量。关闭文件jfilechooser。然后删除该文件。

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();

    }

}
}

此外,如果您希望功能在jfilechooser本身中,我发现此代码可能会证明是有用的。来自Here。要运行此功能,您还需要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);
  }
}

答案 2 :(得分:0)

这是向您的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");
    }
}

代码改编自JavaTechnical的答案。