上一篇中,关于文件搜索器的实现过程中,用到的是递归的算法,即每一次搜索的过程中,就要遍历整个指定的路径,毫无疑问,这样搜索的效率会很低。那么,能不能第一次遍历的时候把遍历到的所有文件都保存在一起,然后进行查找的时候几乎是可以直接获取的方式,这样实现的效率会大大的提高,机会可以做到要把输入的关键字一输入进去,就可以搜索到想要的结果。
而这里我们所说的保存在一起,就是保存在一个map中,然后存储在一个文件中。
这里有四个类:主方法类mainFrame,搜索工具类SearchTool,以及FileProcessThread和ImageDialog,最后一个主要是能够使搜索到的后缀为gif和jpg的文件能够打开。
注意,这里实现的文件搜索器不仅能够搜索到所需要文件的具体路径,还可以根据具体的路径打开文件。
package com.sg.FileSearch2;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
public class mainFrame extends JFrame{
boolean flag=true ;
private JTextField jtf;
String str;
private int Cflag=1;
Map<String, File> allFile;
public static void main(String[]args){
mainFrame mf=new mainFrame();
mf.ShowUI();
}
private void ShowUI() {
this.setTitle("检索一下");
this.setSize(695,880);
this.setLocationRelativeTo(null);
this.setResizable(false);
setLayout(null);
jtf=new JTextField();
//jtf.setForeground(Color.lightGray);
// jtf.setFont(new Font("宋体",0,22));
// jtf.stText("\t\t请输入检索关键字,回车发起检索");
JTextArea jta=new JTextArea();
JScrollPane js=new JScrollPane(jta);
JLabel jl=new JLabel("相关检索结果:");
JLabel j2=new JLabel("选定目录:");
jtf.setBounds(5,10, 680, 40);
jl.setBounds(5, 52, 680, 30);
j2.setBounds(5, 70, 680, 30);
jta.setBounds(5, 96, 680,720);
js.setBounds(5, 96, 680,720);
JPopupMenu pp1=new JPopupMenu();
JPopupMenu pp2=new JPopupMenu();
JMenuItem jm11=new JMenuItem("浏览");
JMenuItem jm12=new JMenuItem("打开");
JMenuItem jm21=new JMenuItem("浏览");
JMenuItem jm22=new JMenuItem("打开文件夹");
JMenuItem jm23=new JMenuItem("自定义打开(gif,jpg)");
JMenuBar jmb = new JMenuBar();
JMenu jmu1=new JMenu("盘符");
JMenu jmu2=new JMenu("关于");
JMenuItem jm31=new JMenuItem("C盘");
JMenuItem jm32=new JMenuItem("D盘");
JMenuItem jm41=new JMenuItem("版本");
pp1.add(jm11);
pp1.add(jm12);
jta.add(pp1);
pp2.add(jm21);
pp2.add(jm22);
pp2.add(jm23);
jta.add(pp2);
jmu1.add(jm31);
jmu1.add(jm32);
jmu2.add(jm41);
//jtf.setFont(f);TextColor(Color.RED);
//jtf.setText("请输入文件的关键字");
this.add(jtf);
this.add(jl);
this.add(j2);
this.add(js);
jmb.add(jmu1);
jmb.add(jmu2);
setJMenuBar(jmb);
this.setVisible(true);
ActionListener openDir2 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if("C盘".equals(command))
{ Cflag=1;
System.out.println("点击了C盘");}
else if("D盘".equals(command))
{ Cflag=2;
System.out.println("点击了d盘");}
else if("版本".equals(command))
JOptionPane.showMessageDialog(jm41, "该检索器为版本一");
if(Cflag==1)
{System.out.println("准备启动C盘");
if(allFile!=null)
allFile.clear();
SearchTool.loadOrCreateIndex("cindex","C:/");
}
else
{System.out.println("准备启动d盘");
if(allFile!=null)
allFile.clear();
SearchTool.loadOrCreateIndex("cindex2","D:/");
}
}
};
jm31.addActionListener(openDir2);
jm32.addActionListener(openDir2);
jm41.addActionListener(openDir2);
SearchTool.loadOrCreateIndex("cindex2","D:/");
//添加键盘监听
jtf.addKeyListener(new KeyListener()
{
@Override
public void keyReleased(KeyEvent e)
{
if(e.getKeyCode()==10)
{ int count=0;
String text = jtf.getText();
if(text.trim().equals(""))
{
jta.setText("");
return;
}
jta.setText("");
Pattern p = Pattern.compile(text);
allFile = SearchTool.allFile;
for (String fileName : allFile.keySet()) {
if(p.matcher(fileName).find())
{ count++;
jta.append(allFile.get(fileName).getAbsolutePath());
jta.append("\r\n");
}
}
jl.setText("检索到"+count+"结果如下:");
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e)
{
// if(flag)
// {
// jtf.setText("");
// flag=false;
// }
}
});
jta.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
jta.setSelectedTextColor(Color.red);
try {
Rectangle rec = jta.modelToView(jta.getCaretPosition());
//获取行数
int line=rec.y / rec.height + 1;
int selectionStart = jta.getLineStartOffset(line-1);
int selectionEnd = jta.getLineEndOffset(line-1);
System.out.println(rec.y / rec.height + 1);
System.out.println(selectionStart+"---->"+selectionEnd);
str=jta.getText(selectionStart,selectionEnd-selectionStart);
System.out.print(str);
// String str1="D:/学习资料/大二下学期/汇编/小资料/debug调试方法.txt1111111111111111111111111";
j2.setText("选定目录:"+str);
// System.out.println(str1);
str = str.replaceAll("\r\n", "");
// str = str.replaceAll("\n", "");
//str=str.replace(" ", "");
System.out.println(str);
System.out.println(str.toLowerCase().endsWith(".txt"));
if (str.toLowerCase().endsWith(".txt") ||str.endsWith(".gif") || str.endsWith(".jpg")
|| str.endsWith(".xml") ||str.endsWith(".png"))
{
System.out.println("1111111111111111");
pp2.show(jta, e.getX(), e.getY());
}
else
{
System.out.println("2222222222222222");
pp1.show(jta, e.getX(), e.getY());
}
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
ActionListener openDir = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
try {
if ("打开文件夹".equals(command)) {
Runtime.getRuntime().exec("cmd /c start " + new File(str).getParent());
} else if ("浏览".equals(command)) {
Runtime.getRuntime().exec(new String[]{"cmd.exe","/C",str});
} else{
System.out.println("12358745412544444444444444");
if (str.endsWith(".gif") ||str.endsWith(".jpg")) {
ImageDialog id = new ImageDialog(str);
id.showUI();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
};
jm11.addActionListener(openDir);
jm12.addActionListener(openDir);
jm21.addActionListener(openDir);
jm22.addActionListener(openDir);
jm23.addActionListener(openDir);
}
}
public class SearchTool {
static Map<String,File> allFile = new HashMap<String, File>();
static List<Thread> ts = new ArrayList<Thread>();
private static void createIndex(String filePath) {
// 创建C: file
File root = new File(filePath);
// 列举下面所有文件
File[] listFiles = root.listFiles();
// 循环
for (File file : listFiles) {
// 如果是文件
if (file.isFile()) {
allFile.put(file.getName(), file);
} else {
// 如果是文件夹,创建线程处理
FileProcessThread tpt = new FileProcessThread(file);
ts.add(tpt);
tpt.start();
}
}
}
public static void loadOrCreateIndex(String indexPath,String filePath) {
File indexFile = new File(indexPath);
if (indexFile.exists()) {
loadIndex(indexPath);
} else {
createIndex(filePath);
saveIndex(indexPath);
}
}
private static void saveIndex(String path) {
// TODO Auto-generated method stub
new Thread() {
public void run() {
ii: while (true) {
for (Thread t : SearchTool.ts) {
System.out.println(t.getState());
if (t.getState() != Thread.State.TERMINATED) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue ii;
}
}
break;
}
try {
File f = new File(path);
if (!f.exists()) {
f.createNewFile();
}
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(SearchTool.allFile);
oos.flush();
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
};
}.start();
}
private static void loadIndex(String path) {
// TODO Auto-generated method stub
try {
FileInputStream fis = new FileInputStream(path);
ObjectInputStream ois = new ObjectInputStream(fis);
SearchTool.allFile.putAll((Map<String, File>) ois.readObject());
System.out.println(SearchTool.allFile.size());
ois.close();
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.sg.FileSearch2;
import java.io.File;
public class FileProcessThread extends Thread {
File file;
public FileProcessThread(File file) {
// TODO Auto-generated constructor stub
this.file = file;
getFile(file);
}
public void getFile(File f)
{
File[] listFiles = f.listFiles();
if(listFiles!=null&& listFiles.length>0 )
for (File ff : listFiles) {
if(f.isFile())
{
System.out.println(f.getAbsolutePath());
SearchTool.allFile.put(f.getName(), f);
}
else
getFile(ff);
}
<pre name="code" class="html">package com.sg.FileSearch2;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
public class ImageDialog extends JDialog implements Runnable {
private String path;
private Image image;
int width;
int height;
public ImageDialog(String path) {
System.out.println("1234567899987654321");
setModal(true);
this.path = path;
ImageIcon imageIcon = new ImageIcon(path);
width = imageIcon.getIconWidth();
height = imageIcon.getIconHeight();
System.out.println(height + "," + width);
setSize(width, height);
image = imageIcon.getImage();
setLocationRelativeTo(null);
setUndecorated(true);
addListener();
new Thread(this).start();
}
private void addListener() {
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ImageDialog.this.dispose();
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image, 0, 0, width, height,null);
}
public void showUI() {
setVisible(true);
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
repaint();
try {
Thread.currentThread().sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}}