Awt simple file searcher and awt simple file searcher

Source: Internet
Author: User
Tags dateformat

Awt simple file searcher and awt simple file searcher

In troubleshooting, Dai Wei's colleagues may find XXX strings from hundreds of compressed log files (in gz format,

In linux, you can use the pipeline command find. /-name '*. gz '| xargx grep 'xxx', but I prefer to work in the window environment.

So I wrote this simple searcher by myself (in fact, I am not familiar with awt and swing, and I will study it slowly ).

First, it looks like this:


To search for a character, perform the following operations:


Let's talk about the key code:

1. A frame is required to be displayed as a top-level window. Everything is included in this frame.

Public void launchFindFrame () {frame = new Frame ("search string"); 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. You need to define buttons, menus, labels, and so on.

Toolkit tk = Toolkit. getdefatooltoolkit (); Dimension screenSize = tk. getScreenSize (); // obtain the size of the physical screen, so that the calculated pop-up frame can be centered Frame frame = null; MenuBar mb = new MenuBar (); // Menu m1 = new Menu ("File"); Menu m2 = new Menu ("Help"); MenuItem mi1 = new MenuItem ("select "); // MenuItem mi2 = new MenuItem ("exit"); MenuItem mi3 = new MenuItem ("about help "); // text prompt area, button Label lbl1 = new Label ("Search Path:"); Label lbl2 = new Label ("search content :"); label lblPath = new Label ("null"); TextField tf = new TextField (20); Button btn = new Button ("Search "); button expBtn = new Button ("Export search result"); TextArea ta = new TextArea (); Panel innerp = new Panel (new FlowLayout (FlowLayout. LEFT); // three panelPanel p1 for large frame layout = 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 ("Searching", Label. CENTER); Button breakBtn = new Button ("stop searching"); Thread findFileExecThread = null; // the Thread of the search file algorithm class references FindFileExecutor ffe = null; // The search file algorithm class
3. Add event listening to buttons

// Select the file event listener mi1.addActionListener (new ActionListener () {public void actionreceivmed (ActionEvent e) {JFileChooser fc = new JFileChooser (); fc. setFileSelectionMode (JFileChooser. FILES_AND_DIRECTORIES); // either a file or a folder 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 actionreceivmed (ActionEvent e) {JOptionPane. showMessageDialog (null, "please contact chengsheng.wang@zznode.com if you have any questions", "Reminder", JOptionPane. PLAIN_MESSAGE );}});
// The Search button listens to btn. addActionListener (new ActionListener () {public void actionreceivmed (ActionEvent e) {if (lblPath. getText () = null | "". equals (lblPath. getText () | "null ". equals (lblPath. getText () {JOptionPane. showMessageDialog (null, "the search path cannot be blank! "," Prompt ", JOptionPane. WARNING_MESSAGE);} else if (tf. getText () = null | "". equals (tf. getText () {JOptionPane. showMessageDialog (null, "the search content cannot be blank! "," Prompt ", JOptionPane. WARNING_MESSAGE);} else {initFindAction (); final Dialog d = new Dialog (frame); d. setResizable (false); d. setModal (true); d. setTitle ("Progress prompt"); d. setBackground (Color. LIGHT_GRAY); d. setLayout (new BorderLayout (); Panel np = new Panel (); // terminate the event listening of the Search button. Use the flag to automatically exit the search file logic, instead of forcing the interrupt thread, you cannot force the interrupt to breakBtn. addActionListener (new ActionListener () {public void actionreceivmed (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 (invalid wevent e) {d. setVisible (false); d. dispose () ;}}); d. setBounds (frame. getX () + 100, frame. getY () + 100,280,120); // set the location to display it // execute the search algorithm ffe = new FindFileExecutor (lblPath. getText (), tf. getText (), progressbar, ta); findFileExecThread = new Thread (ffe); findFileExecThread. start (); d. setVisible (true );}}});
// Export search result button event expBtn. addActionListener (new ActionListener () {public void actionreceivmed (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 ("Export search result"); chooser. setSelectedFile (new File (name); // filter to display and save only the txt File chooser. add ChoosableFileFilter (new FileFilter () {public boolean accept (File f) {if (f. getName (). endsWith ("txt") | f. isDirectory () {return true;} else {return false;} public String getDescription () {return "text file (*. txt) ";}}); int intRetVal = chooser. showSaveDialog (frame); if (intRetVal = JFileChooser. APPROVE_OPTION) {if (new File (chooser. getSelectedFile (). getPath ()). exists () {int confirmRetVal = JOpti OnPane. showConfirmDialog (null, "the file already exists. Do you want to overwrite the file? "," OK ", JOptionPane. WARNING_MESSAGE); if (JOptionPane. YES_NO_OPTION! = ConfirmRetVal) {return ;}// export 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, "data exported successfully. Do you want to open this file? "," OK ", JOptionPane. WARNING_MESSAGE); if (openRetVal = JOptionPane. YES_NO_OPTION) {Desktop d = Desktop. getDesktop (); // since jdk1.6 call the default file opening function of the system. try {d. open (new File (chooser. getSelectedFile (). getPath ();} catch (IOException e1) {e1.printStackTrace () ;}}} else {JOptionPane. showMessageDialog (null, "No search results! "," Prompt ", JOptionPane. WARNING_MESSAGE );}}});
4. progress bar Initialization

// Listener for events that initialize the progress bar public void initBar () {progressbar. setOrientation (JProgressBar. HORIZONTAL); progressbar. setMinimum (0); progressbar. set maximum (100); progressbar. setValue (0); progressbar. setStringPainted (true); progressbar. addChangeListener (new ChangeListener () {/*** progressbar each time. if the value of setValue () is changed, the listener Method */public void stateChanged (ChangeEvent e) {int value = progressbar is triggered. getValue (); if (e. getSource () = Progressbar) {barLbl. setText ("Completed search:" + ffe. getCurrentIndex () + "files, found" + ffe. getMatchCount () + "matching record"); barLbl. setForeground (Color. blue);} if (value = progressbar. getMaximum () {barLbl. setText ("finally finished, from" + ffe. getTotalOfFiles () + "upload to" + ffe. getMatchCount () + "matching records! "); BreakBtn. setLabel ("close") ;}}); progressbar. setPreferredSize (new Dimension (300, 20); progressbar. setBorderPainted (true); progressbar. setBackground (Color. pink );}
5. Search for the file Algorithm (this is omitted and everyone on Earth knows it)

After the code is complete, use the j2ewiz.exe tool to package the jar into an exe file and double-click it to run it.



Final example:



The source code, packaging tools, and finished product links are attached at the end:

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

Click to download

This article is only intended for communication and learning purposes. It is very simple to write. Please forgive me!





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.