• We just launched and are currently in beta. Join us as we build and grow the community.

Search Application in JAVA

heyitskurt

Dynamic Code Analyzer
H Rep
0
0
0
Rep
0
H Vouches
0
0
0
Vouches
0
Posts
109
Likes
58
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
TUTORIAL NO 4

In this tutorial you will learn:

1. Reading from a file
2. Multi Threading
3. Recursion
4. Event handling
5. Layout Manager
6. JAVA awt basics
7. JAVA swing basics
8. Adapters
9. Anonymous classes

Today I am going to teach you how to make a file searching program. It can search any file and display it’s contents.

interface_0.png


In this tutorial we will be working in JAVA SWING. The first thing that we are going to do is setting up a JFrame and adding the required panels and Components.

Basic step:
Download and install ECLIPSE and set up a JAVA PROJECT. Then create a new class and name it SearchApp. Then follow the steps

1.IMPORT STATEMENTS
First of all write these import statements in your .java file

  1. import

    javax.swing.*

    ;
  2. import

    java.awt.*

    ;
  3. import

    java.awt.event.*

    ;
  4. import

    java.io.*

    ;

We require event import for mouse click , awt and swing imports for visual design. For this tutorial we will only be using one public class and we will be extending it from JFrame (i.e inheritance)
2.SETTING UP THE FRAME CLASS
  1. public

    class

    SearchApp extends

    JFrame

    implements

    Runnable

    {

  2. private

    File

    [

    ]

    myfile;
  3. private

    static

    byte

    b[

    ]

    ;

    // for reading characters in file

  4. int

    directories_count =

    0

    ;
  5. String

    directory;

  6. private

    JTextField

    t_field =

    new

    JTextField

    (

    ""

    , 20

    )

    ;

    // for file name
  7. private

    JTextField

    p_field =

    new

    JTextField

    (

    ""

    , 30

    )

    ;

    // for diplaying the file path
  8. private

    JTextArea

    t_areaUpper =

    new

    JTextArea

    (

    " FILE CONTENTS WILL BE DISPLAYED HERE "

    )

    ;

    //upper text area
  9. private

    JTextArea

    t_areaLower =

    new

    JTextArea

    (

    " DIRECTORIES WILL BE DISPLAYED HERE "

    )

    ;

    //lower text area
  10. private

    JLabel

    file_label=

    new

    JLabel

    (

    "File Name :"

    )

    ;

    //file name label
  11. private

    JLabel

    dir_label =

    new

    JLabel

    (

    "Directory :"

    )

    ;

    //directory label
  12. private

    JLabel

    status =

    new

    JLabel

    (

    "Status: Ready "

    )

    ;

    //status label
  13. private

    JLabel

    path =

    new

    JLabel

    (

    "Path: "

    )

    ;

    //path label

  14. private

    JScrollPane

    spUpper=

    new

    JScrollPane

    (

    t_areaUpper)

    ;

    //scrollpane for upper text area
  15. private

    JScrollPane

    spLower=

    new

    JScrollPane

    (

    t_areaLower)

    ;

    //scrollpane for lower text area

  16. private

    JComboBox

    jcb =

    new

    JComboBox

    (

    )

    ;

    //combo box for directories
  17. private

    JButton

    search =

    new

    JButton

    (

    "Search"

    )

    ;

    // search button

  18. private

    String

    file_name;

    //for storing file name
  19. private

    String

    dir;

    //for storing directories
  20. boolean

    file_found;

    //checking if the file is found
  21. private

    String

    file_text =

    ""

    ;

    //for displaying file contents
  22. private

    Thread

    t;

Create a public frame class by extending it from JFrame and implementing the runnable interface for multithreading. Now create all the required variables. File array reference for getting the root directories then a counter to count the number of directories on your system. Byte array for reading bytes in the file .After that declare all the text fields and labels according to the User Interface shown in the picture above. Then we need a label to set the status, two scroll panes for two text areas (Upper and Lower) one to show the contents of the file other to show the traversed directories, combo box to show the directories on your system, then finally the Search. Other than that variables to store file name, directory and a boolean to change the status whether file is found or not.

3. WRITING THE CONTSTUCTOR
We will do everything in a constructor so that the jframe gets setup whenever we create the object of that JFrame. Now writing the constructor
  1. SearchApp(

    )

    {

  2. directories_count =

    File

    .listRoots

    (

    )

    .length

    ;

    //counting total disk drives
  3. myfile =

    File

    .listRoots

    (

    )

    ;

    // a file object for storing root directories

  4. for

    (

    int

    i=

    0

    ;

    i<

    directories_count;

    i++

    )
  5. jcb.addItem

    (

    myfile[

    i]

    )

    ;

    // adding directories in comboBox

  6. JPanel

    up =

    new

    JPanel

    (

    )

    ;

    //panel to add north
  7. JPanel

    center =

    new

    JPanel

    (

    new

    GridLayout

    (

    2

    ,1

    )

    )

    ;

    //panel to add in the center

  8. add(

    up, "North"

    )

    ;

    //adding a panel north
  9. add(

    center,"Center"

    )

    ;

    //adding a panel center

  10. up.add

    (

    file_label)

    ;

    //file name label
  11. up.add

    (

    t_field)

    ;

    // text field
  12. up.add

    (

    dir_label)

    ;

    //directory label
  13. up.add

    (

    jcb)

    ;

    //combo box
  14. up.add

    (

    search)

    ;

    //search button
  15. up.add

    (

    status)

    ;

    //status label
  16. up.add

    (

    path)

    ;

    //path label
  17. up.add

    (

    p_field)

    ;

    //path field

  18. setTitle(

    "Search Application"

    )

    ;
  19. setDefaultCloseOperation(

    JFrame

    .EXIT_ON_CLOSE

    )

    ;
  20. setSize(

    1000

    , 700

    )

    ;

    //frame size
  21. setVisible(

    true

    )

    ;

  22. center.add

    (

    spUpper)

    ;

    // adding upper text area with scroll pane
  23. center.add

    (

    spLower)

    ;

    // adding lower text area with scroll pane

First of all we will count the number of directories and save the root directories in our file array. Then we will add all the directories name to the combo box. After that we will created two jpanels and added one to north position and other one in the center. We set the layout of the second jpanel to gridlayout so that we can divide it in two parts. Then we added all the labels, text fields and search button as shown in the picture above in up panel and the two text fields in the center panel. After that we setup the frame size and visibility. (NOTE : Till now it’s quite similar to our antivirus program. But Keep noting the changes ).

  1. search.addMouseListener

    (

    new

    MouseAdapter

    (

    )

    {

  2. public

    void

    mouseClicked(

    MouseEvent

    me)

    {

  3. p_field.setText

    (

    " "

    )

    ;
  4. file_text =

    ""

    ;

    //empty the string on click
  5. t_areaLower.setText

    (

    " "

    )

    ;

    //empty the t_area on click

  6. file_name =

    t_field.getText

    (

    )

    ;

    //get file name form text field

  7. dir =

    jcb.getSelectedItem

    (

    )

    .toString

    (

    )

    ;

    //get directory
  8. dir +=

    "\\

    "

    ;
  9. status.setText

    (

    "Searching.."

    )

    ;

    //set status
  10. startThread(

    )

    ;

    //start the thread
  11. }
  12. }

    )

    ;
  13. }

    // end constructor

In the mouselistener we created an anonymous MouseAdapter class (Remember: anonymous class is the one in which you only have to create one object). Now we override the mouse clicked function. The first thing we need to clear the text every time on click after that we need to get the file name from the text field and directory from the combo box. Then we set the status of our app. Then we started the thread and end the class ,listener and the constructor. The startThread() function is defined below.

4. START THREAD FUNCTION:
  1. public

    void

    startThread(

    )

    {
  2. t =

    new

    Thread

    (

    this

    )

    ;
  3. t.start

    (

    )

    ;
  4. }

In this function we created an instance of thread class and pass it the runnable component of the class using this. Then we start the thread.

5. SEARCH FUNCTION:
  1. public

    void

    Search(

    String

    v_dir, File

    v)

    {
  2. File

    [

    ]

    list =

    v.listFiles

    (

    )

    ;

    //listing files

  3. if

    (

    list !=

    null

    )

    {

    //checking so that nullpointerException cannot occur
  4. for

    (

    File

    subfile :

    list)

    {

    //listing every sub directory

  5. t_areaLower.append

    (

    ""

    +

    v.getAbsolutePath

    (

    )

    )

    ;

    //showing in text area
  6. t_areaLower.append

    (

    "\n

    "

    )

    ;

    // new line after printing a directory
  7. File

    v_file =

    new

    File

    (

    v.getAbsolutePath

    (

    )

    , file_name)

    ;

    // getting the path of file

  8. if

    (

    subfile.isDirectory

    (

    )

    )

    {
  9. Search(

    v_dir, subfile)

    ;

    //if more directories then search through them
  10. }

  11. if

    (

    v_dir.equalsIgnoreCase

    (

    subfile.getName

    (

    )

    )

    )

    {

    //compare file names
  12. file_found =

    true

    ;

    //if file is found
  13. readFile(

    subfile)

    ;

    // read the contents

  14. status.setText

    (

    "Status :File Found "

    )

    ;

    //set the status
  15. p_field.setText

    (

    subfile.getAbsolutePath

    (

    )

    )

    ;
  16. }
  17. }

    //end for
  18. }

    //end if
  19. }

    //end search

First of all we list the files in the directory and check if there are files present or not. If files are present then we move on and start appending the paths to the text area. After that we check whether the current iteration of the loop points towards a directory or not if it does we call the search function again i.e recursively. Then we check the file names whether they are equal or not if they are equal then we set the Boolean variable to true for setting the label and call the readFile function to read the contents of the file. After that we set the status and set the path where the file is found.

6. READ FILE FUNCTION:
  1. public

    void

    readFile(

    File

    myfile)

    {

  2. try

    {
  3. if

    (

    myfile.exists

    (

    )

    )

    {

  4. FileInputStream

    fis =

    new

    FileInputStream

    (

    myfile)

    ;
  5. b =

    new

    byte

    [

    (

    int

    )

    myfile.length

    (

    )

    ]

    ;

    // creating byte array
  6. try

    {
  7. fis.read

    (

    b)

    ;

    //reading bytes and storing in b
  8. }

    catch

    (

    IOException

    e)

    {

    }

  9. for

    (

    int

    i=

    0

    ;

    i<

    b.length

    ;

    i++

    )
  10. file_text +=

    (

    char

    )

    b[

    i]

    ;

    //convert bytes to char and store in string
  11. }
  12. }

    catch

    (

    FileNotFoundException

    e)

    {

    }

    //catch exceptions
  13. t_areaUpper.setText

    (

    file_text)

    ;

    //display file contens in upper text area
  14. }

Here we are reading the file contents if the file with the specified name exists. First of all we created the object of the FileInputStream class and passed the file object (i.e myfile) to the input stream. Then we specified the byte array length to the length of the file and started reading the bytes from the file into the byte array. REMEMBER we added the filing functions in a try catch block to handle the Input, Ouput and File not found exceptions. After reading we converted the bytes to characters using type casting and appended them in variable string file_text. In the end we set the contents of upper text area to file_text variable (REMEMBER: it has all the data stored in it).

7. OVERRIDING THE RUN FUNCTION:
  1. @Override
  2. public

    void

    run(

    )

    {
  3. Search(

    file_name, new

    File

    (

    dir)

    )

    ;

    //call the function when thread is created
  4. if

    (

    file_found ==

    false

    )
  5. status.setText

    (

    "File Not Found !"

    )

    ;
  6. }

After implementing the runnable interface we will override the run function and call the Search function in it by passing the file name and directory to it’s parameters. Now we need to set the status after all the directories are traversed, so we set the status according to the value of our Boolean variable (i.e file_found) depending on file, if it’s spread or not.

8. DEFINING THE MAIN FUNCTION
  1. public

    static

    void

    main(

    String

    [

    ]

    args)

    {
  2. new

    SearchApp(

    )

    ;
  3. }

    //end main
  4. }

    // end SearchApp Frame

In the main function we only created the object of the JFrame class and our application is complete.

OUPUT:
output_27.png



Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,526

323,535

Top