Paid for writing

In case you like my writing and would like me to write for your website, then please leave a comment to any of my blog article, mentioning your Email Id and I will reply back. Thanks

Tuesday, January 20, 2009

Developing a Simple Text Reader in Java

The following is the source code to create a simple application in Java, in order to read the contents of a text file

/////////////// TextFileReader.java /////////////////////

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.BufferedReader;

public class TextFileReader implements ActionListener
{

JButton fileButton;
JTextField fileText;
public JTextArea contentsArea;
JPanel filePanel;
JFrame frame;
JScrollPane contentsPane;

public TextFileReader()
{

frame=new JFrame();
frame.setTitle("Text File Reader");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

fileButton=new JButton("Browse");
fileButton.addActionListener(this);
fileText=new JTextField(30);
fileText.setEditable(false);

filePanel=new JPanel();
filePanel.setLayout(new FlowLayout(FlowLayout.CENTER));

filePanel.add(fileText);
filePanel.add(fileButton);

contentsArea=new JTextArea();
contentsArea.setEditable(false);

contentsPane=new JScrollPane(contentsArea);


frame.setLayout(new BorderLayout());

frame.add(filePanel,BorderLayout.NORTH);

frame.add(contentsPane, BorderLayout.CENTER);

frame.setVisible(true);
frame.setSize(600,600);

}

public static void main(String args[])
{
new TextFileReader();

}

public void actionPerformed(ActionEvent ae)
{
String fileContents,fileName;
contentsArea.setText(null);

if(ae.getSource()==fileButton)
{



JFileChooser fc=new JFileChooser("C:\\");

fc.showOpenDialog(frame);

if(fc.APPROVE_OPTION==1);
{


fileName=fc.getSelectedFile().getPath();
fileText.setText(fileName);

try
{
FileReader fr=new FileReader(fileName);

BufferedReader br=new BufferedReader(fr);

while((fileContents=br.readLine())!=null)
{
//System.out.println(br.read());

contentsArea.append(fileContents);
contentsArea.append("\n");
}
}
catch(Exception e)
{
System.out.println(e);
}
}

}
}


}

0 comments: