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

Reading from and Writing to a Text File in Java

Gor510

Eccentric Innovator
G Rep
0
0
0
Rep
0
G Vouches
0
0
0
Vouches
0
Posts
151
Likes
20
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 400 XP
Introduction:
This tutorial demonstrate the method of reading from and writing to a text file in Java. Java has two type of files: Binary and Text. Text file is processed as a sequence of characters where as Binary file is processed a sequence of bytes. This application has 4 JButtons for reading, writing, exiting, and clearing the Display Area. Also It has a display area where we can type the data to be written to text and in the same area content from file are displayed.

Step 1: Creating GUI Components
Create the four buttons, label, text area and text field. Text field is used to take file name from user.

  1. JTextArea

    display=

    new

    JTextArea

    (

    )

    ;
  2. JButton

    read=

    new

    JButton

    (

    "Read From File"

    )

    ;
  3. JButton

    write=

    new

    JButton

    (

    "Write To File"

    )

    ;
  4. JButton

    clear=

    new

    JButton

    (

    "Clear Display Area"

    )

    ;
  5. JButton

    exit=

    new

    JButton

    (

    "Exit"

    )

    ;

  6. JTextField

    name=

    new

    JTextField

    (

    20

    )

    ;
  7. JLabel

    prompt=

    new

    JLabel

    (

    "File Name : "

    , JLabel

    .RIGHT

    )

    ;
  8. JPanel

    commandPanel=

    new

    JPanel

    (

    )

    ;

    //panel for holding above buttons



Step 2: Initializing Constructor


In the constructor of class, we add the created components to the frame and add ActionListeners to it. A panel is created with Grid Layout having 2 rows and 3 columns and 1 pixel gap between the components. All the buttons and text field is added to this panel. This panel is added to the North of the main frame. Display area occupies the center area of the frame with scroll pane. Scroll Pane is added when the contents of the component(area) extends the component.

  1. public

    TextIO(

    )

    {
  2. super

    (

    "Text IO Demo"

    )

    ;

    //Title of the frame
  3. read.addActionListener

    (

    this

    )

    ;
  4. write.addActionListener

    (

    this

    )

    ;
  5. clear.addActionListener

    (

    this

    )

    ;
  6. exit.addActionListener

    (

    this

    )

    ;
  7. commandPanel.setLayout

    (

    new

    GridLayout

    (

    2

    ,3

    ,1

    ,1

    )

    )

    ;

    //grid with two rows and three columns
  8. commandPanel.add

    (

    prompt)

    ;
  9. commandPanel.add

    (

    name)

    ;
  10. commandPanel.add

    (

    clear)

    ;
  11. commandPanel.add

    (

    read)

    ;
  12. commandPanel.add

    (

    write)

    ;
  13. commandPanel.add

    (

    exit)

    ;
  14. display.setLineWrap

    (

    true

    )

    ;
  15. this

    .setLayout

    (

    new

    BorderLayout

    (

    )

    )

    ;
  16. this

    .add

    (

    commandPanel, BorderLayout

    .NORTH

    )

    ;
  17. this

    .add

    (

    new

    JScrollPane

    (

    display)

    )

    ;
  18. this

    .add

    (

    display,BorderLayout

    .CENTER

    )

    ;
  19. }


Step 3: Defining read/write functions


The main part is to read and write the data. For reading from a file we require the BufferedReader object which provides buffering for characters input stream(text files). This object takes FileReader object so as to read from a file. try {} catch block is used to handle if there is any error reading the file.

  1. private

    void

    readTextFile(

    JTextArea

    display, String

    fileName)
  2. {
  3. try

    {
  4. BufferedReader

    inStream=

    new

    BufferedReader

    (

    new

    FileReader

    (

    fileName)

    )

    ;
  5. String

    line=

    inStream.readLine

    (

    )

    ;

    //read the next line every time.
  6. while

    (

    line!=

    null

    )
  7. {
  8. display.append

    (

    line +

    "\n

    "

    )

    ;
  9. line=

    inStream.readLine

    (

    )

    ;
  10. }
  11. inStream.close

    (

    )

    ;
  12. }
  13. catch

    (

    FileNotFoundException

    e)

    {

  14. display.setText

    (

    "IO Error: "

    +

    fileName +

    " Not Found. "

    +

    "\n

    "

    )

    ;
  15. e.printStackTrace

    (

    )

    ;


  16. }
  17. catch

    (

    IOException

    e)

    {
  18. display.setText

    (

    "IO Error: "

    +

    e.getMessage

    (

    )

    +

    "\n

    "

    )

    ;
  19. e.printStackTrace

    (

    )

    ;

  20. }
  21. }

write function works similar except that it write the data of the complete text area at one time. FileWriter object is used to write the data to file. This object takes a file name, if file is already there it overrides the file content and if file is not there then new file is created. If the file can not be created then a message is displayed.
  1. try

    {
  2. FileWriter

    ostream=

    new

    FileWriter

    (

    fileName)

    ;
  3. ostream.write

    (

    display.getText

    (

    )

    )

    ;
  4. JOptionPane

    .showMessageDialog

    (

    null

    ,"Data written to file"

    , "Successful Write Operation"

    ,JOptionPane

    .INFORMATION_MESSAGE

    )

    ;
  5. ostream.close

    (

    )

    ;
  6. }
  7. catch

    (

    IOException

    e)

    {
  8. display.setText

    (

    "IO Error: "

    +

    fileName +

    " Not Found. "

    +

    "\n

    "

    )

    ;
  9. e.printStackTrace

    (

    )

    ;

  10. }
  11. }


Step 4: Writing Action Listeners for the Buttons


When a user clicks on read, write, clear or exit button, appropriate action is performed. When read button is clicked readTextFile() function is called. Similary all other button's events are handled as follows.
  1. String

    fileName=

    name.getText

    (

    )

    ;

    //content of text area
  2. if

    (

    ae.getSource

    (

    )

    ==

    read)

    // get source of event
  3. {
  4. display.setText

    (

    ""

    )

    ;
  5. readTextFile(

    display,fileName)

    ;
  6. }
  7. else

    if

    (

    ae.getSource

    (

    )

    ==

    write)
  8. writeTextFile(

    display, fileName)

    ;
  9. else

    if

    (

    ae.getSource

    (

    )

    ==

    clear)
  10. display.setText

    (

    ""

    )

    ;

    //clears the display area
  11. else

    if

    (

    ae.getSource

    (

    )

    ==

    exit)
  12. {
  13. System

    .exit

    (

    0

    )

    ;

  14. }


Step 5: Writing main() function


From here, execution starts, object of the class is created and some properties of frame are set.


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

452,292

325,536

325,544

Top