Q.Write a java program to accept directory name in TextField and display list of files and subdirectories in List Control from that directory by clicking on Button.[25 M]
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class DirectoryListAWT extends Frame implements ActionListener
{
TextField tf;
Button btn;
List lst;
Label lbl;
public DirectoryListAWT()
{
setLayout(new FlowLayout());
lbl = new Label("Enter Directory Name:");
tf = new TextField(30);
btn = new Button("Show Files");
lst = new List(15, true);
add(lbl);
add(tf);
add(btn);
add(lst);
btn.addActionListener(this);
setTitle("Directory File List");
setSize(400,400);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
lst.removeAll();
String dirname = tf.getText();
File f = new File(dirname);
if(f.exists() && f.isDirectory())
{
String files[] = f.list();
for(int i=0;i<files.length;i++)
{
File temp = new File(dirname + File.separator + files[i]);
if(temp.isDirectory())
lst.add(files[i] + " <DIR>");
else
lst.add(files[i] + " <FILE>");
}
}
else
{
lst.add("Invalid Directory");
}
}
public static void main(String args[])
{
new DirectoryListAWT();
}
}