awt简易的文件搜索器

8 篇文章 0 订阅
5 篇文章 0 订阅

代维的同事排查问题,可能会遇到从成百上千个压缩日志文件(gz格式)中搜索XXX字符串等,

在linux环境,应该可以用管道命令find ./ -name '*.gz' |xargx grep 'xxx'搞定,不过本人更喜欢在window环境下,自己想办法搞定。

于是就自己动手写了这个简易的搜索器(其实对awt和swing都不太熟悉,慢慢研究来的)。

先上个截图,大致的样子就是这样:


搜索某个字符的操作是这样的:


闲话不说了,说说关键代码:

1.需要一个frame,作为顶级窗口显示,所有的东西,都是包括在这个frame中

	public void launchFindFrame(){
		
		frame = new Frame("检索字符串");
		frame.setSize(520, 360);
		frame.setLocation(screenSize.width/3, screenSize.height/3);
		frame.addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		frame.setLayout(new BorderLayout());		
		initMenu();
		initLayout();
		initBar();
		frame.setVisible(true);
	}
2.需要定义一些button、menu、label等等

        Toolkit tk = Toolkit.getDefaultToolkit();
	Dimension screenSize = tk.getScreenSize();//获取物理屏幕的大小,以便计算弹出frame可以居中
	
	Frame frame = null;
	
	MenuBar mb = new MenuBar();//菜单栏
	Menu m1 = new Menu("File");
	Menu m2 = new Menu("Help");
	MenuItem mi1 = new MenuItem("选择");//菜单下拉项
	MenuItem mi2 = new MenuItem("退出");
	MenuItem mi3 = new MenuItem("关于帮助");
	
	//文本提示区、按钮
	Label lbl1 = new Label("搜索路径:");
	Label lbl2 = new Label("搜索内容:");
	Label lblPath = new Label("空");
	TextField tf = new TextField(20);
	Button btn = new Button("搜索");
	Button expBtn = new Button("导出搜索结果");
	TextArea ta = new TextArea();
	Panel innerp = new Panel(new FlowLayout(FlowLayout.LEFT));
	
	//用于大框架布局的3个panel
	Panel p1 = new Panel(new BorderLayout());
	Panel p2 = new Panel(new FlowLayout(FlowLayout.LEFT));	
	Panel p3 = new Panel(new BorderLayout());	
	//进度条相关显示
	JProgressBar progressbar = new JProgressBar();
	Label barLbl = new Label("玩命搜索中",Label.CENTER);
	Button breakBtn = new Button("停止搜索");
	
	Thread findFileExecThread = null;//搜索文件算法类的线程引用
	FindFileExecutor ffe = null;     //搜索文件算法类
3.给各个按钮加上事件监听

                //菜单按钮,选择文件事件监听
		mi1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fc = new JFileChooser();
				fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);//既可以是文件也可以是文件夹
				int intRetVal = fc.showOpenDialog(frame);
				if (intRetVal == JFileChooser.APPROVE_OPTION) {
					lblPath.setSize(screenSize.width, lblPath.getHeight());
					lblPath.setText(fc.getSelectedFile().getPath());
				}
			}
		});
		mi3.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "有任何问题请联系chengsheng.wang@zznode.com", "友情提醒",JOptionPane.PLAIN_MESSAGE); 
			}
		});
                //搜索按钮的事情监听
		btn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				if(lblPath.getText() == null || "".equals(lblPath.getText()) || "空".equals(lblPath.getText())){
					JOptionPane.showMessageDialog(null, "搜索路径不能为空!", "提示",JOptionPane.WARNING_MESSAGE); 
				} else if(tf.getText() == null || "".equals(tf.getText())){
					JOptionPane.showMessageDialog(null, "搜索内容不能为空!", "提示",JOptionPane.WARNING_MESSAGE); 
				} else {
					initFindAction();
	 				final Dialog d = new Dialog(frame);
					d.setResizable(false);
					d.setModal(true);
					d.setTitle("进度提示");
					d.setBackground(Color.LIGHT_GRAY);
					d.setLayout(new BorderLayout());
					Panel np = new Panel();
					//终止搜索按钮的事情监听,用flag标识让搜索文件的逻辑自动退出,而不是强制interrupt线程,当然你也强制interrupt不了
					breakBtn.addActionListener(new ActionListener(){
						public void actionPerformed(ActionEvent e) {
							if(findFileExecThread != null && findFileExecThread.isAlive()){
								ffe.setFlag(true);
							}
							d.setVisible(false);
							d.dispose();
						}
					});
					np.add(breakBtn);
					d.add(np,BorderLayout.NORTH);
					d.add(barLbl,BorderLayout.CENTER);
					d.add(progressbar,BorderLayout.SOUTH);
					d.addWindowListener(new WindowAdapter(){
						@Override
						public void windowClosing(WindowEvent e) {
							d.setVisible(false);
							d.dispose();
						}
					});
					d.setBounds(frame.getX()+100, frame.getY()+100,280,120);//设定使其出现位置
					
					//执行搜索算法
					ffe = new FindFileExecutor(lblPath.getText(),tf.getText(),progressbar,ta);
					findFileExecThread = new Thread(ffe);
					findFileExecThread.start();
					
					d.setVisible(true);
				}
			}
		});
                //导出搜索结果按钮事件
		expBtn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				if(ta.getText() != null && !"".equals(ta.getText())){
					SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd_HHmmss");  
		            String name = dateformat.format(new Date()) + ".txt";  
					JFileChooser chooser = new JFileChooser();  
		            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  
		            chooser.setDialogType(JFileChooser.SAVE_DIALOG);   
		            chooser.setDialogTitle("导出搜索结果");
		            chooser.setSelectedFile(new File(name));
		            //过滤只显示和保存txt文件
		            chooser.addChoosableFileFilter(new FileFilter(){  
		                public boolean accept(File f) {  
		                    if (f.getName().endsWith("txt") || f.isDirectory()) {  
		                         return true;   
		                    }else{  
		                        return false;   
		                    }  
		                }  
		                public String getDescription() {  
		                    return "文本文件(*.txt)";  
		                }  
		            });
		            int intRetVal = chooser.showSaveDialog(frame);
					if (intRetVal == JFileChooser.APPROVE_OPTION) {
						if(new File(chooser.getSelectedFile().getPath()).exists()){
							int confirmRetVal = JOptionPane.showConfirmDialog(null, "文件已经存在,是否要覆盖该文件?", "确认",JOptionPane.WARNING_MESSAGE);
							if(JOptionPane.YES_NO_OPTION != confirmRetVal){
								return;
							} 
						}
						//导出
						BufferedWriter bw = null;
						try {
							bw = new BufferedWriter(new FileWriter(new File(chooser.getSelectedFile().getPath())));
							String[] textAreaLines = ta.getText().trim().split("\r\n");
							for(String line : textAreaLines){
								bw.write(line);
								bw.newLine();
							}
						} catch (IOException e1) {
							e1.printStackTrace();
						} finally {
							if(bw != null){
								try {
									bw.close();
								} catch (IOException e2) {
									e2.printStackTrace();
								}
							}
						}
						int openRetVal = JOptionPane.showConfirmDialog(null, "导出数据成功,要打开该文件吗?", "确认",JOptionPane.WARNING_MESSAGE);
						if(openRetVal == JOptionPane.YES_NO_OPTION){
							Desktop d = Desktop.getDesktop();//since jdk1.6 调用系统默认的打开文件功能
							try {
								d.open(new File(chooser.getSelectedFile().getPath()));
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
					}
				} else {
					JOptionPane.showMessageDialog(null, "无搜索结果!", "提示",JOptionPane.WARNING_MESSAGE);
				}
			}
		});
4.进度条的初始化

	//初始化进度条的事件监听
	public void initBar(){
		progressbar.setOrientation(JProgressBar.HORIZONTAL);
		progressbar.setMinimum(0);
		progressbar.setMaximum(100);
		progressbar.setValue(0);
		progressbar.setStringPainted(true);
		progressbar.addChangeListener(new ChangeListener(){
			/**
			 * 每次progressbar.setValue()时,如果value值改变,则触发此监听方法
			 */
			public void stateChanged(ChangeEvent e) {
				int value = progressbar.getValue();
				if (e.getSource() == progressbar) {
					barLbl.setText("已完成搜索:" + ffe.getCurrentIndex() + "个文件,共发现"+ffe.getMatchCount()+"处匹配记录");
					barLbl.setForeground(Color.blue);
				}
				if(value == progressbar.getMaximum()){
					barLbl.setText("终于撸完了,从"+ffe.getTotalOfFiles()+"个文件中撸到"+ffe.getMatchCount()+"个匹配记录!");
					breakBtn.setLabel("关闭");
				}
			}
		});
		progressbar.setPreferredSize(new Dimension(300, 20));
		progressbar.setBorderPainted(true);
		progressbar.setBackground(Color.pink);
	}
5.搜索文件算法(这个省略,地球人都知道)

代码完成后,用j2ewiz.exe工具把jar包装成exe文件,双击运行。



最后成样:



末尾附上源代码、包装工具以及成品的链接:

http://download.csdn.net/detail/wangchsh2008/8733305

点击下载

本文仅限交流学习使用,写得很简陋,请见谅!





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
设计一个简易记事本需要考虑以下几个方面: 1. 用户界面设计:需要设计一个简单易用的用户界面,包括菜单栏、工具栏、文本编辑区和状态栏等。 2. 文本输入输出:需要实现文本输入、编辑和输出的功能,可以使用Java Swing中的JTextArea组件。 3. 文件读写:需要实现文件的读写功能,可以使用Java IO流。 4. 搜索和替换:需要实现文本搜索和替换功能,可以使用Java字符串操作函数。 下面是一个简单的Java记事本的代码实现: ``` import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import javax.swing.*; public class Notepad extends JFrame implements ActionListener { JTextArea textArea; JMenuBar menuBar; JMenu fileMenu, editMenu; JMenuItem newFile, openFile, saveFile, saveAsFile, exit, cut, copy, paste, find, replace; JToolBar toolBar; JButton newButton, openButton, saveButton, cutButton, copyButton, pasteButton, findButton, replaceButton; public Notepad() { setTitle("Java Notepad"); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 创建菜单栏 menuBar = new JMenuBar(); fileMenu = new JMenu("文件"); editMenu = new JMenu("编辑"); menuBar.add(fileMenu); menuBar.add(editMenu); // 创建文件菜单项 newFile = new JMenuItem("新建"); openFile = new JMenuItem("打开"); saveFile = new JMenuItem("保存"); saveAsFile = new JMenuItem("另存为"); exit = new JMenuItem("退出"); fileMenu.add(newFile); fileMenu.add(openFile); fileMenu.add(saveFile); fileMenu.add(saveAsFile); fileMenu.addSeparator(); fileMenu.add(exit); // 创建编辑菜单项 cut = new JMenuItem("剪切"); copy = new JMenuItem("复制"); paste = new JMenuItem("粘贴"); find = new JMenuItem("查找"); replace = new JMenuItem("替换"); editMenu.add(cut); editMenu.add(copy); editMenu.add(paste); editMenu.addSeparator(); editMenu.add(find); editMenu.add(replace); // 创建工具栏 toolBar = new JToolBar(); newButton = new JButton(new ImageIcon("new.png")); openButton = new JButton(new ImageIcon("open.png")); saveButton = new JButton(new ImageIcon("save.png")); cutButton = new JButton(new ImageIcon("cut.png")); copyButton = new JButton(new ImageIcon("copy.png")); pasteButton = new JButton(new ImageIcon("paste.png")); findButton = new JButton(new ImageIcon("find.png")); replaceButton = new JButton(new ImageIcon("replace.png")); toolBar.add(newButton); toolBar.add(openButton); toolBar.add(saveButton); toolBar.addSeparator(); toolBar.add(cutButton); toolBar.add(copyButton); toolBar.add(pasteButton); toolBar.addSeparator(); toolBar.add(findButton); toolBar.add(replaceButton); // 创建文本编辑区 textArea = new JTextArea(); JScrollPane scrollPane = new JScrollPane(textArea); // 添加组件到窗口 setJMenuBar(menuBar); add(toolBar, BorderLayout.NORTH); add(scrollPane, BorderLayout.CENTER); // 添加监听器 newFile.addActionListener(this); openFile.addActionListener(this); saveFile.addActionListener(this); saveAsFile.addActionListener(this); exit.addActionListener(this); cut.addActionListener(this); copy.addActionListener(this); paste.addActionListener(this); find.addActionListener(this); replace.addActionListener(this); newButton.addActionListener(this); openButton.addActionListener(this); saveButton.addActionListener(this); cutButton.addActionListener(this); copyButton.addActionListener(this); pasteButton.addActionListener(this); findButton.addActionListener(this); replaceButton.addActionListener(this); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == newFile || e.getSource() == newButton) { textArea.setText(""); setTitle("Java Notepad - 新建"); } else if (e.getSource() == openFile || e.getSource() == openButton) { JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { try { BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile())); String line = null; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(System.getProperty("line.separator")); } reader.close(); textArea.setText(stringBuilder.toString()); setTitle("Java Notepad - " + fileChooser.getSelectedFile().getName()); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "打开文件出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } else if (e.getSource() == saveFile || e.getSource() == saveButton) { if (getTitle().endsWith("新建")) { JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile())); writer.write(textArea.getText()); writer.close(); setTitle("Java Notepad - " + fileChooser.getSelectedFile().getName()); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "保存文件出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } else { try { BufferedWriter writer = new BufferedWriter(new FileWriter(getTitle().substring(14))); writer.write(textArea.getText()); writer.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "保存文件出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } else if (e.getSource() == saveAsFile) { JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile())); writer.write(textArea.getText()); writer.close(); setTitle("Java Notepad - " + fileChooser.getSelectedFile().getName()); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "保存文件出错:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } else if (e.getSource() == exit) { System.exit(0); } else if (e.getSource() == cut || e.getSource() == cutButton) { textArea.cut(); } else if (e.getSource() == copy || e.getSource() == copyButton) { textArea.copy(); } else if (e.getSource() == paste || e.getSource() == pasteButton) { textArea.paste(); } else if (e.getSource() == find || e.getSource() == findButton) { String searchText = JOptionPane.showInputDialog(this, "查找:"); if (searchText != null && !searchText.equals("")) { int index = textArea.getText().indexOf(searchText); if (index != -1) { textArea.setCaretPosition(index); textArea.select(index, index + searchText.length()); } else { JOptionPane.showMessageDialog(this, "未找到:" + searchText, "提示", JOptionPane.INFORMATION_MESSAGE); } } } else if (e.getSource() == replace || e.getSource() == replaceButton) { String searchText = JOptionPane.showInputDialog(this, "查找:"); if (searchText != null && !searchText.equals("")) { String replaceText = JOptionPane.showInputDialog(this, "替换为:"); if (replaceText != null) { String content = textArea.getText(); int index = content.indexOf(searchText); if (index != -1) { textArea.setText(content.substring(0, index) + replaceText + content.substring(index + searchText.length())); } else { JOptionPane.showMessageDialog(this, "未找到:" + searchText, "提示", JOptionPane.INFORMATION_MESSAGE); } } } } } public static void main(String[] args) { new Notepad(); } } ``` 这个记事本实现了基本的文本输入、编辑、输出和文件读写功能,同时提供了菜单栏和工具栏操作。您可以根据自己的需求进行扩展和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值