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.
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.
public TextIO(){
super("Text IO Demo"); //Title of the frame
read.addActionListener(this);
write.addActionListener(this);
clear.addActionListener(this);
exit.addActionListener(this);
commandPanel.
setLayout(new GridLayout(2,
3,
1,
1)); //grid with two rows and three columns
commandPanel.add(prompt);
commandPanel.add(name);
commandPanel.add(clear);
commandPanel.add(read);
commandPanel.add(write);
commandPanel.add(exit);
display.setLineWrap(true);
}
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.
{
try{
String line
=inStream.
readLine(); //read the next line every time.
while(line!=null)
{
display.append(line + "\n");
line=inStream.readLine();
}
inStream.close();
}
display.setText("IO Error: " + fileName + " Not Found. "+"\n");
e.printStackTrace();
}
display.setText("IO Error: " + e.getMessage() +"\n");
e.printStackTrace();
}
}
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.
try{
ostream.write(display.getText());
JOptionPane.
showMessageDialog(null,
"Data written to file",
"Successful Write Operation",
JOptionPane.
INFORMATION_MESSAGE);
ostream.close();
}
display.setText("IO Error: " + fileName + " Not Found. "+"\n");
e.printStackTrace();
}
}
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.
String fileName
=name.
getText(); //content of text area
if(ae.getSource()==read)// get source of event
{
display.setText("");
readTextFile(display,fileName);
}
else if(ae.getSource()==write)
writeTextFile(display, fileName);
else if(ae.getSource()==clear)
display.setText(""); //clears the display area
else if(ae.getSource()==exit)
{
}
Step 5: Writing main() function
From here, execution starts, object of the class is created and some properties of frame are set.