首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

File与资料搜索器

2012-10-24 
File与文件搜索器[sizesmall][/size]经过最近对于File类的学习,我了解到了在电脑中,不论是目录还是文件,

File与文件搜索器
[size=small][/size]
    经过最近对于File类的学习,我了解到了在电脑中,不论是目录还是文件,都可以用File进行存储和操作,File类本身提供了非常多常用的方法,如:isDrectory(),listRoots()等,几乎全部的文件操作都可以通过这些已定义的方法来完成。
    目前阶段我学习到的对于File的使用主要就是进行目录或者文件的检索,由此制作了一个简易的文件搜索器,步骤如下:

1、制作一个文件搜索器的窗体,设置大小以及各种属性
    JFrame jf = new JFrame("文件搜索器");
    jf.setSize(600, 400);
    jf.setDefaultCloseOperation(3);
    jf.setResizable(false);
    jf.setLocationRelativeTo(null);
    jf.setLayout(null);
2、在窗体上添加两个面板,一个面板放置搜索按钮与输入路径的文本框等,另一个用来显示搜索结果
    // 面板
    public void init(){
    JPanel jp = new JPanel();
    jp.setBounds(0, 0, 120, 400);
    jp.setBackground(Color.white);
    jp.setLayout(new GridLayout(12, 1));
    jf.add(jp);
    JLabel lb = new JLabel("选择搜索范围");
    jp.add(lb);
    JComboBox cb = new JComboBox(list);
    cb.addItem("选择目录");
    cb.setSelectedItem(cb);
    cb.setEditable(true);
    jp.add(cb);
    JLabel lb1 = new JLabel("按内容搜索");
    jp.add(lb1);
    JTextField tf = new JTextField(20);
    jp.add(tf);

    JButton btn = new JButton("搜索");
    btn.setActionCommand("Search");
    jp.add(btn);
    // JButton btn1 = new JButton("停止");
    // btn1.setActionCommand("Stop");
    // jp.add(btn1);
    JTextArea ta = new JTextArea();
    ta.setVisible(true);
    ta.setEditable(false);
    ta.setBackground(Color.white);
    ta.setLineWrap(true);
    JScrollPane pane = new JScrollPane(ta);
    pane.setBounds(120, 0, 480, 400);
    jf.add(pane);
3、添加监听器,并设置窗体可见
    FileListener fl = new FileListener(tf, cb, ta);

    cb.addActionListener(fl);
    //tf.addActionListener(fl);
    btn.addActionListener(fl);
    // btn1.addActionListener(fl);
    jf.setVisible(true);
    }
4、主函数(FileResearch)
    public static void main(String[] args) {
    FileSearch fs = new FileSearch();
    //调用此方法在下拉列表中显示当前电脑上已经存在的磁盘
    fs.listRoots();
    //调用绘制窗体的方法
    fs.init();
    }

    public void listRoots() {
    File file = new File("");
    File[] rootlist = file.listRoots();
    int number = rootlist.length;
    list = new String[number];
    for (int i = 0; i < rootlist.length; i++) {
      this.list[i] = rootlist[i].getAbsolutePath();
      }
    System.out.println("总共有" + number + "个盘");
    }
5、监听器的编写
    //定义一个构造函数,将需要的窗体中的部分传过来,便于操作
    public FileListener(JTextField tf, JComboBox cb, JTextArea ta) {
    this.tf = tf;
    this.cb = cb;
    this.ta = ta;
    }

    //重写方法
    public void actionPerformed(ActionEvent e) {
            //获取输入框中的内容和,即希望搜索到的文件的关键字
content = tf.getText();
            //获取用户选择的盘的路径作为搜索的根路径
root = (String) cb.getSelectedItem();
            //如果用户选择自己选择路径,则绘制选择对话框
if (e.getActionCommand().equals("Search")) {
// 选择目录时
if (cb.getSelectedItem().equals("选择目录")) {
// 绘制对话框,选择文件拷贝的具体路径
JFileChooser chooser = new JFileChooser();
int option = chooser.showDialog(null, "选择");
chooser.setFileSelectionMode  (JFileChooser.FILES_AND_DIRECTORIES);
//NC:要添加点击取消按钮的动作事项,否则退出会报错
if(option == JFileChooser.CANCEL_OPTION){
return;
}
chooser.setControlButtonsAreShown(true);
// 获取输入
File file = chooser.getCurrentDirectory();
// 路径
String path = file.getAbsolutePath();
File file1 = new File(path);
listFile = file1.listFiles();
File file2 = chooser.getSelectedFile();
content = file2.getName();
//调用所写的搜索方法
int count = searchContent(listFile);
ta.append("共找到文件" + count + "个" + "\n" + "\n" + "\n");
} else {
           // 指定盘,无需弹出对话框,直接进行查找
if (root == null || root.equals("")) {
ta.append("该路径不存在!");
File file = new File("");
listFile = file.listRoots();
//for (int i = 0; i < listFile.length; i++) {
// ta.append(listFile[i].getName()+"\n");
// ta.append(listFile[i].getAbsolutePath()+"\n");
//System.out.println(listFile[i].getName() + "\n");
//System.out.println(listFile[i].getAbsolutePath() + "\n");
//}
} else {
                       //路径存在,但是无搜索关键字,列出盘下所有文件
if (content == null || content.length() == 0) {
//System.out.println("===================>");
File file = new File(root);
listFile = file.listFiles();
int count = search(listFile);
ta.append("共找到文件" + count + "个" + "\n" + "\n" + "\n");
//System.out.println("列数为" + ta.getLineCount());
} else {
//按关键字搜索
File file = new File(root);
listFile = file.listFiles();
int count = searchContent(listFile);
// System.out.println("content is not null" + count);
ta.append("共找到文件" + count + "个" + "\n" + "\n" + "\n");
}
        }
     }
             }
// if (e.getActionCommand().equals("Stop")) {
// ta.append("you press Stop!");
// }
          }
6、搜索方法的编写
    //无关键字时的搜索方法
    private int search(File[] file) {
    int count = 0;
    if (file == null || file.length == 0) {
   return 0;
     }
    for (int i = 0; i < file.length; i++) {
  File filenew = file[i];
if (filenew.isDirectory()) {
            File[] tempFile = filenew.listFiles();
count += search(tempFile);
}
if (filenew.isFile()) {
            count++;
ta.append("文件:" + filenew.getAbsolutePath() + "\n");
}
  }
return count;
         }
    //有关键字时候的搜索方法
    private int searchContent(File[] file) {
            int count = 0;
if (file == null || file.length == 0) {
System.out.println("search is 0");
return 0;
}
for (int i = 0; i < file.length; i++) {
File filenew = file[i];
// 包含字符
if (filenew.isDirectory()) {
File[] tempFile = filenew.listFiles();
count += searchContent(tempFile);
}

if (filenew.isFile()) {
String path = filenew.getAbsolutePath();
if (path.indexOf(content) != -1) {
count++;
ta.append("文件:" + filenew.getAbsolutePath() + "\n");
}
        }
      }
return count;
  }
在编写完成整个文件搜索器后,我感觉到了自己有很多程序细节处理上的不足,比如在弹出对话框时没有设置CANCLE_OPTION选项,使得如果不在对话框中进行选择,直接点击取消或者关闭会显示空指针异常。还有在编写两种搜索方法的时候,直接把相同的代码部分进行了复制,而代码之中递归的部分的函数名字没有修改,使得方法调用混乱,搜索的结果出现了很大偏差,这让我记住了在今后的学习中一定要细心,使用数据时注意判断其是否为空,是否会抛出异常等,而且代码尽量不要使用复制,这样会导致出错的频率增高,同时更改时还不易被发现。
                                                                 艾儿~~~

热点排行