awt簡易的檔案搜尋器,awt簡易檔案搜尋器

來源:互聯網
上載者:User

awt簡易的檔案搜尋器,awt簡易檔案搜尋器

代維的同事排查問題,可能會遇到從成百上千個壓縮記錄檔(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(){@Overridepublic 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個panelPanel 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(){@Overridepublic 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

點擊下載

本文僅限交流學習使用,寫得很簡陋,請見諒!





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.