一个简单的文件搜索器,代码如下:
public class FileQuery extends JFrame{
private JTextField field_path; //输入路径的搜索框
private JTextArea area_show; // 显示搜索结果的文本域
JLabel label_countFile,label_countDirectory; //显示文件、文件夹数量
private int countFile = 0,countDirectory=0; //文件、文件夹的个数
public static void main(String[] args) {
FileQuery fileQuery=new FileQuery();
fileQuery.showUI();
}
/**
* 显示界面的方法
*/
public void showUI(){
setTitle("文件搜索器");
setSize(450,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setLayout(new FlowLayout());
//创建组件对象
JLabel label_path=new JLabel("路径:");
JLabel label_file=new JLabel("文件数量");
JLabel label_directory=new JLabel("文件夹数量");
label_countFile=new JLabel();
label_countDirectory=new JLabel();
field_path=new JTextField(25);
JButton button_query=new JButton("搜索");
area_show=new JTextArea(18,35);
JScrollPane jsp=new JScrollPane(area_show);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//添加组件到窗体
add(label_path);
add(field_path);
add(button_query);
add(label_file);
add(label_countFile);
add(label_directory);
add(label_countDirectory);
add(jsp,BorderLayout.CENTER);
//给搜索按钮添加监听器
button_query.addActionListener(actionListener);
//可见
setVisible(true);
}
//监听
ActionListener actionListener=new ActionListener() {
//实现监听器中的抽象的监控方法
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//获取用户在界面上输入的路径
String path=field_path.getText();
//根据路径进行查询
queryFile(path);
label_countFile.setText(countFile+"");
label_countDirectory.setText((--countDirectory)+"");
}
};
/**
* 搜索指定目录下的文件,并将搜索到的文件的绝对路径显示到文本域中
* @param path
*/
public void queryFile(String path){
File file=new File(path);
if(file.exists()){
if(file.isFile()){ //如果file是具体的文件
countFile++;
String absPath=file.getAbsolutePath();
System.out.println(absPath);
area_show.append(file.getAbsolutePath()+"\r\n"); // 在显示域追加结果回车换行
}else if(file.isDirectory()){ //如果file是目录
countDirectory++;
File [ ] files= file.listFiles();
for(int i=0;i<files.length;i++){
File f=files[i];
System.out.println(f.getAbsolutePath());
queryFile(f.getAbsolutePath());
}
}
}else{
System.out.println("该路径无效。。。。。");
}
}
}
实现效果如下: