java中的文件重复

时间:2012-05-09 20:13:26

标签: java swing file jlist

我已使用JList通过JFileChooser向我的vector添加了一些文件。我试图通过检查特定文件是否在JList中可用来系统地进行。例如,如果我添加一个名为“abc.xml”的文件,我会立即检查JList中是否存在该文件。

此外,我想检查文件是否只重复一次。如果它被重复多次('abc.xml','abc.xml',...),则应该有一条错误消息,指出该文件被多次添加。

我在这里发布我的完整代码;

         public Test() 
{
    setTitle("EXAMPLE");
    getContentPane().setLayout(new MigLayout("", "[][][][][grow][][][][][][][]
               [][][grow][grow][][][grow][][][][][][][grow]", "[][][][][][][][grow]
              [grow][][][][][][][grow][]"));

    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileChooser.setMultiSelectionEnabled(true);
    getContentPane().add(fileChooser, "cell 0 1 3 16");

    JScrollPane scrollPane = new JScrollPane();
    getContentPane().add(scrollPane, "cell 23 2 3 15,grow");

    vector = new Vector<File>();
    final JList list = new JList(vector);
    scrollPane.setViewportView(list);


    JButton btnNewButton = new JButton(" Add          ");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for (File file : fileChooser.getSelectedFiles()) {
                        vector.addElement(file);
                 }
                //System.out.println("Added..!!");
                list.updateUI();

            }
    });
    getContentPane().add(btnNewButton, "cell 4 0");



    JButton btnNewButton_1 = new JButton(" Remove   ");
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(list.getSelectedIndices().length > 0) {
                  int[] selectedIndices = list.getSelectedIndices();
                  for (int i = selectedIndices.length-1; i >=0; i--) {
                        vector.removeElementAt(i);
                    } 
                   }
                    //System.out.println("Removed..!!");
                    list.updateUI();

        }   
        });
    getContentPane().add(btnNewButton_1, "cell 4 2");

    JButton btnNewButton_2 = new JButton(" Check       ");
    btnNewButton_2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            ***File file = fileChooser.getSelectedFile();
            boolean found = false;
            for (File f : vector) {
                 if (file.getName().equals(f.getName())) {
                     found = true;
                     break;
                 }
            }
            if (!found) {
                vector.add(file);
                fireIntervalAdded(this, vector.size()-1, vector.size()-1);
            } else {
                // Abusive usage of an exception
                JOptionPane.showMessageDialog(null, "File " + file.getName() + " 
                already added");

            }***
         });

           public static void main(String args[]) {        
          // Create an instance of the test application         
           Test mainFrame = new Test();        
           mainFrame.pack();         
           mainFrame.setVisible(true);     
  }

我得到的是一个msg框,告诉文件已经添加,即使文件只出现一次。

我的期望是,当文件添加一次时,它不应显示任何内容。但是当它被添加多次时,它才会显示已经添加文件的消息。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

好的,这是你描述的一个例子。我不太确定拒绝添加文件的条件是什么。这个是基于名称的,但我想知道您是不是在使用File.equals()来寻找getCanonicalFile()。我在代码中也给出了评论。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Test {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                initUI();
            }
        });
    }

    public static class MyListModel extends AbstractListModel {

        private Vector<File> files = new Vector<File>();

        public void addFilesToModel(File[] f) {
            for (File file : f) {
                addFileToModel(file);
            }
        }

        public void addFileToModel(File file) throws IllegalArgumentException {
            boolean found = false;
            // file = file.getCanonicalFile();
            for (File file2 : files) {
                // file2.getCanonicalFile().equals(file) + throw IOException
                if (file2.getName().equals(file.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                files.add(file);
                fireIntervalAdded(this, files.size() - 1, files.size() - 1);
            } else {
                // Abusive usage of an exception
                throw new IllegalArgumentException("File " + file.getName() + " already added");
            }
        }

        @Override
        public int getSize() {
            return files.size();
        }

        @Override
        public Object getElementAt(int index) {
            return files.get(index);
        }

    }

    private static File lastFolder;

    protected static void initUI() {
        JFrame frame = new JFrame("test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        final MyListModel model = new MyListModel();
        JList list = new JList(model);
        final JButton button = new JButton("Add files...");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                if (lastFolder != null) {
                    chooser.setCurrentDirectory(lastFolder);
                }
                chooser.setMultiSelectionEnabled(true);
                chooser.showDialog(button, "Add files");
                if (chooser.getSelectedFiles() != null) {
                    for (File file : chooser.getSelectedFiles()) {
                        try {
                            model.addFileToModel(file);
                        } catch (IllegalArgumentException e1) {
                            JOptionPane.showMessageDialog(button, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                    lastFolder = chooser.getCurrentDirectory();
                }
            }
        });
        panel.add(new JScrollPane(list));
        panel.add(button);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

修改


除了您的代码不完整之外,我设法安排它并让它工作但它真的很不完美。我也摆脱了MigLayout,因为它需要一个额外的库。随意把它放回去。

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Test extends JFrame {

    Vector<File> vector;
    JPanel root;
    private MyListModel model;

    public class MyListModel extends AbstractListModel {

        public void addFilesToModel(File[] f) {
            for (File file : f) {
                addFileToModel(file);
            }
        }

        public void addFileToModel(File file) throws IllegalArgumentException {
            boolean found = false;
            // file = file.getCanonicalFile();
            for (File file2 : vector) {
                // file2.getCanonicalFile().equals(file) + throw IOException
                if (file2.getName().equals(file.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                vector.add(file);
                fireIntervalAdded(this, vector.size() - 1, vector.size() - 1);
            } else {
                // Abusive usage of an exception
                throw new IllegalArgumentException("File " + file.getName() + " already added");
            }
        }

        public void removeFileFromModel(File file) throws IllegalArgumentException {
            int index = vector.indexOf(file);
            File removed = vector.remove(index);
            if (removed != null) {
                fireIntervalRemoved(this, index, index);
            } else {
                // Nothing was removed
            }
        }

        public void removeFilesFromModel(File[] files) {
            for (File f : files) {
                removeFileFromModel(f);
            }
        }

        @Override
        public int getSize() {
            return vector.size();
        }

        @Override
        public Object getElementAt(int index) {
            return vector.get(index);
        }

    }

    public Test() {
        super("EXAMPLE");
        root = new JPanel(new GridBagLayout());
        vector = new Vector<File>();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridheight = 2;
        getContentPane().add(root);
        final JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setMultiSelectionEnabled(true);
        root.add(fileChooser, gbc);
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.ipadx = 5;
        gbc.ipady = 5;
        gbc.gridheight = 1;
        gbc.gridwidth = 3;
        gbc.gridx = 1;

        vector = new Vector<File>();
        model = new MyListModel();
        final JList list = new JList(model);
        JScrollPane scrollPane = new JScrollPane(list);
        root.add(scrollPane, gbc);
        gbc.gridwidth = 1;
        gbc.weightx = 0;
        gbc.weighty = 0;
        gbc.anchor = GridBagConstraints.CENTER;
        final JButton btnNewButton = new JButton("Add");
        btnNewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (File file : fileChooser.getSelectedFiles()) {
                    try {
                        model.addFileToModel(file);
                    } catch (IllegalArgumentException e1) {
                        showError(btnNewButton, file);
                    }
                }
            }
        });
        gbc.gridy = 1;
        root.add(btnNewButton, gbc);

        JButton btnNewButton_1 = new JButton("Remove");
        btnNewButton_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (list.getSelectedIndices().length > 0) {
                    for (Object file : list.getSelectedValues()) {
                        model.removeFileFromModel((File) file);
                    }
                }
            }
        });
        gbc.gridx++;
        root.add(btnNewButton_1, gbc);

        final JButton btnNewButton_2 = new JButton("Check");
        btnNewButton_2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                File file = fileChooser.getSelectedFile();
                boolean found = false;
                for (File f : vector) {
                    if (file.getName().equals(f.getName())) {
                        found = true;
                        break;
                    }
                }
                if (found) {
                    showError(btnNewButton_2, file);
                } else {
                    JOptionPane.showMessageDialog(btnNewButton_2, "File " + file.getAbsolutePath() + " is not in the list yet");
                }
            }

        });
        gbc.gridx++;
        root.add(btnNewButton_2, gbc);
    }

    private void showError(Component parent, File file) {
        JOptionPane.showMessageDialog(parent, "File " + file.getName() + " already added");
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Test mainFrame = new Test();
                mainFrame.pack();
                mainFrame.setVisible(true);
            }
        });
    }
}

答案 1 :(得分:0)

vector.contains(fileName)

从第一个开始?