Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

java - How to Delete files from the directory by specifying it in the output application

package com.tools;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton; 
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer; 
import javax.swing.DefaultListModel;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.AbstractListModel;
import java.awt.Color;
import javax.swing.JTextArea;
import java.awt.List;
import javax.swing.JScrollPane;

public class CleaningToolV2 {

private JFrame frame;

private JTextField folderName;
private JTextField date_from;
private JTextField date_to;
JRadioButton radio_max = new JRadioButton("max");
JRadioButton radio_png = new JRadioButton("png");
JRadioButton radio_psd = new JRadioButton("psd");
JRadioButton radio_tiff = new JRadioButton("tiff");
JComboBox<String> comboBox = new JComboBox<String>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");


JTextArea textArea = new JTextArea();
ArrayList<File> selectedFiles = new ArrayList<File>();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                CleaningToolV2 window = new CleaningToolV2();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public CleaningToolV2() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    CleaningToolV2 thisObj = this;

    frame = new JFrame();
    frame.setBounds(100, 100, 450, 539);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    String toDayDate = simpleDateFormat.format(new Date());

    DefaultComboBoxModel<String> comboModel1 = new DefaultComboBoxModel<String>(new String[] {"Furn", "Unfurn"});
    DefaultComboBoxModel<String> comboModel2 = new DefaultComboBoxModel<String>(new String[] {"Temp"});
    comboBox.setModel(comboModel1);
    comboBox.setBounds(20, 174, 145, 27);
    frame.getContentPane().add(comboBox);


    folderName = new JTextField();
    folderName.setBounds(20, 53, 283, 26);
    frame.getContentPane().add(folderName);
    folderName.setColumns(10);

    JButton btnBrowse = new JButton("Browse");
    btnBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc=new JFileChooser(folderName.getText());
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int i=fc.showOpenDialog(frame);    
            if(i==JFileChooser.APPROVE_OPTION){    
                File f=fc.getSelectedFile();    
                String filepath=f.getPath();    
                folderName.setText(filepath);
            }    
        }
    });
    btnBrowse.setBounds(315, 53, 117, 29);
    frame.getContentPane().add(btnBrowse);

    JLabel label_ext = new JLabel("Extensions and File name token");
    label_ext.setBounds(20, 111, 250, 16);
    frame.getContentPane().add(label_ext);

    radio_png.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            comboBox.setModel(comboModel1);
        }
    });
    radio_png.setBounds(20, 139, 78, 23);
    frame.getContentPane().add(radio_png);

    radio_max.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            comboBox.setModel(comboModel2);
        }
    });
    radio_max.setBounds(130, 139, 71, 23);
    frame.getContentPane().add(radio_max);

    JLabel label_folder = new JLabel("Select folder");
    label_folder.setBounds(20, 25, 107, 16);
    frame.getContentPane().add(label_folder);

    JLabel lblSelectTimeFrame = new JLabel("Enter time frame (DD/MM/YYYY)");
    lblSelectTimeFrame.setBounds(20, 235, 267, 16);
    frame.getContentPane().add(lblSelectTimeFrame);

    date_from = new JTextField();
    date_from.setBounds(71, 263, 130, 26);
    frame.getContentPane().add(date_from);
    date_from.setColumns(10);
    date_from.setText(toDayDate);

    date_to = new JTextField();
    date_to.setColumns(10);
    date_to.setBounds(286, 263, 130, 26);
    date_to.setText(toDayDate);
    frame.getContentPane().add(date_to);

    JLabel label_time_from = new JLabel("From :");
    label_time_from.setBounds(20, 268, 57, 16);
    frame.getContentPane().add(label_time_from);

    JLabel label_time_to = new JLabel("To :");
    label_time_to.setBounds(243, 268, 44, 16);
    frame.getContentPane().add(label_time_to);

    JButton btnClearAllFiles = new JButton("Clear All Files");
    btnClearAllFiles.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for(File f:selectedFiles) {
                f.delete();
            }
            thisObj.refreshList();
        }
    });
    btnClearAllFiles.setBounds(184, 482, 117, 29);
    frame.getContentPane().add(btnClearAllFiles);

    radio_psd.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            comboBox.setModel(comboModel1);
        }
    });
    radio_psd.setBounds(232, 139, 71, 23);
    frame.getContentPane().add(radio_psd);

    radio_tiff.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            comboBox.setModel(comboModel1);
        }
    });
    radio_tiff.setBounds(333, 139, 71, 23);
    frame.getContentPane().add(radio_tiff);

    ButtonGroup bgroup = new ButtonGroup();
    bgroup.add(radio_png);
    bgroup.add(radio_max);
    bgroup.add(radio_psd);
    bgroup.add(radio_tiff);
    radio_png.setSelected(true);

    JLabel label_selected_files = new JLabel("Selected Files");
    label_selected_files.setBounds(20, 318, 127, 16);
    frame.getContentPane().add(label_selected_files);


    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(20, 346, 396, 124);
    frame.getContentPane().add(scrollPane);

    textArea.setEditable(false);
    scrollPane.setViewportView(textArea);

    JButton btnFilterFiles = new JButton("Filter Files");
    btnFilterFiles.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            thisObj.refreshList();
        }
    });
    btnFilterFiles.setBounds(130, 313, 117, 29);
    frame.getContentPane().add(btnFilterFiles);
}

public void refreshList() {
    File folder = new File(folderName.getText());
    File[] listOfFiles = folder.listFiles();
    selectedFiles = new ArrayList<File>();
    String fileNames = "";  
    String selectedItem = comboBox.getSelectedItem().toString().toLowerCase();
    for (int i = 0; i < listOfFiles.length; i++) {
      Date modified = new Date(listOfFiles[i].lastModified());
      String modiDateString = simpleDateFormat.format(modified);
      String from_text = date_from.getText();
      String to_text = date_to.getText();
      if (listOfFiles[i].isFile() && modiDateString.compareTo(from_text) >= 0 && modiDateString.compareTo(to_text) <= 0) {
          String fileName = listOfFiles[i].getAbsoluteFile().getAbsolutePath();
          String ext = this.getSelectedFileExt();
          if(fileName.toLowerCase().endsWith("."+ext) && fileName.toLowerCase().indexOf("_"+selectedItem) > -1) {
              fileNames += listOfFiles[i].getAbsoluteFile().getAbsolutePath() + "
";
              selectedFiles.add(listOfFiles[i]);
          }
      } 
    }
    textArea.setText(fileNames);
}

private String getSelectedFileExt() {
    String ext;
    if(radio_max.isSelected()) {
        ext = "max";
    } else if(radio_psd.isSelected()) {
        ext = "psd";
    } else if(radio_tiff.isSelected()) {
        ext = "tiff";
    } else {
        ext = "png";
    }
    return ext;
}

}

here it was deleting the files if i give exact folder location. but what i am trying to get it is it has to search the directory which conrtains subfolders also it has to search along the sub folders and delete the specified files (eg- file name will be borrry_furn) which was specified in the dropdown

plz help me thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

it has to search the directory which conrtains subfolders also it has to search along the sub folders

Your method to search a directory needs to be recursive.

Here is an example of a recursive method that lists the files in all the sub directories:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableFile extends JFrame
    implements ActionListener, Runnable
{
    JTable table;
    DefaultTableModel model;
    JTextField path;
    JLabel currentFile;
    JButton getFiles;
    int totalFiles;
    int totalDirectories;

    public TableFile()
    {
        path = new JTextField("C:\java");
        add(path, BorderLayout.PAGE_START );

        getFiles = new JButton( "Get Files" );
        getFiles.addActionListener( this );
        add(getFiles, BorderLayout.LINE_START );

        String[] columnNames = {"IsFile", "Name"};

        model = new DefaultTableModel(columnNames, 0);
        table = new JTable( model );

        JScrollPane scrollPane = new JScrollPane( table );
        add(scrollPane, BorderLayout.PAGE_END);

        currentFile = new JLabel(" ");
//      add(currentFile, BorderLayout.PAGE_END); // displays filename in label
    }

    public void actionPerformed(ActionEvent e)
    {
        model.setNumRows(0);

        new Thread( this ).start();

        table.requestFocusInWindow();
    }

    public void run()
    {
        totalFiles = 0;
        totalDirectories = 0;
        listFiles( new File( path.getText() ) );
        System.out.println("Directories: " + totalDirectories);
        System.out.println("Files      : " + totalFiles);
    }

    private void listFiles(File dir)
    {
        updateTable( dir );
        totalDirectories++;
        System.out.println("Processing directory: " + dir);

        //  add a delay to demonstrate processing one directory at a time

        try { Thread.sleep(500); }
        catch(Exception e) {}

        File[ ] entries = dir.listFiles( );
        int size = entries == null ? 0 : entries.length;

        for(int j = 0; j < size; j++)
        {
            if (entries[j].isDirectory( ))
            {
                listFiles( entries[j] );
            }
            else
            {
                updateTable( entries[j] );
                currentFile.setText( entries[j].toString() );
                totalFiles++;
            }
        }
    }

    private void updateTable(final File file)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                Vector<Object> row = new Vector<Object>(2);
                row.addElement( new Boolean( file.isFile() ) );
                row.addElement( file.toString() );
                model.addRow( row );
                int rowCount = table.getRowCount() - 1;
                table.changeSelection(rowCount, rowCount, false, false);
            }
        });
    }

    public static void main(String[] args)
    {
        TableFile frame = new TableFile();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...