事例

平时在无论在家里还是公司,总会有些文件不能删除。
于是突发奇想,做个强力删除java小工具。

实现

浏览----找到你要删除的文件---选择

强力删除---确定

代码

	package fileDelete;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class fileDelete extends JFrame implements ActionListener  {
	JLabel jl;
	JTextField jtf;
	JButton jb1, jb2;
	JPanel jp, jp1;

	public static void main(String[] args) {
		new fileDelete();

	}

	public fileDelete() {
		jl = new JLabel("输入文件或文件夹路径:");
		jtf = new JTextField(50);
		jb1 = new JButton("强力删除");
		jb2 = new JButton("浏览...");

		jp = new JPanel();
		jp1 = new JPanel();
		jp1.add(jtf);
		jp1.add(jb2);
		jp.add(jl);
		jp.add(jp1);
		jp.add(jb1);
		jb2.addActionListener(this);
		jb1.addActionListener(this);

		this.add(jp);
		this.setLayout(new GridLayout(1, 1));
		this.setTitle("强力删除");
		this.setSize(600, 150);
		this.setLocation(400, 200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		this.setResizable(true);

	}

	public void actionPerformed(ActionEvent e) {

		if (e.getSource() == jb2) {
			JFileChooser jfc = new JFileChooser();
			jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			jfc.showDialog(new JLabel(), "选择");
			File file = jfc.getSelectedFile();
			String filepath =file.getAbsolutePath();
			if (file.isDirectory()) {
				jtf.setText(filepath);
			} else if (file.isFile()) {
				jtf.setText(filepath);
			}

		}
		if (e.getSource() == jb1) {
			File file = new File(jtf.getText());
			if(!file.exists()) {
				JOptionPane.showMessageDialog(null, "请选择你要删除的文件!\n无效的文件或文件夹!");
			}else if (file.isFile()) {
				file.delete();
				JOptionPane.showMessageDialog(null, "恭喜文件删除成功!");
				
			}else if(file.isDirectory()) {
				File[] tem=file.listFiles();
				for(int i=0;i<tem.length;i++) {
					if(tem[i].isDirectory()){
						String delDir= new String(jtf.getText()+"/"+tem[i].getName());				
				}else {
					tem[i].delete();
				}
				}


				file.delete();
					JOptionPane.showMessageDialog(null, "恭喜文件夹删除成功!");
				jtf.setText("");
			
		
			}
		}
}

}