更改第下面的样例程序ViewFile.java,编写一个程序,列出一个文件夹下的所有Java文件名。(建议文件名:ListJavaFiles.java)样例为//ViewFile.java:Readatextfileandstoreitinatextare...
更改第下面的样例程序ViewFile.java,编写一个程序,列出一个文件夹下的所有Java文件名。(建议文件名:ListJavaFiles.java)
样例为
// ViewFile.java: Read a text file and store it in a text area
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ViewFile extends MyFrameWithExitHandling implements ActionListener
{
// Button to view view
private JButton jbtView = new JButton("View");
// Text field to receive file name
private JTextField jtf = new JTextField(12);
// Text area to display file
private JTextArea jta = new JTextArea();
// Main method
public static void main(String[] args)
{
ViewFile frame = new ViewFile();
frame.setTitle("View File");
frame.setSize(400, 300);
frame.setVisible(true);
}
// Constructor
public ViewFile()
{
// Panel p to hold a label, a text field, and a button
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(new Label("Filename"), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
jtf.setBackground(Color.yellow);
jtf.setForeground(Color.red);
p.add(jbtView, BorderLayout.EAST);
// Add jta to a scroll pane
JScrollPane jsp = new JScrollPane(jta);
// Add jsp and p to the frame
getContentPane().add(jsp, BorderLayout.CENTER);
getContentPane().add(p, BorderLayout.SOUTH);
// Register listener
jbtView.addActionListener(this);
}
// Handle the "View" button
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbtView)
{
showFile();
}
}
// Display the file in the text area
private void showFile()
{
// Use a BufferedStream to read text from the file
BufferedReader infile = null;
// Get file name from the text field
String filename = jtf.getText().trim();
String inLine;
try
{
// Create a buffered stream
infile = new BufferedReader(new FileReader(filename));
// Read a line
inLine = infile.readLine();
boolean firstLine = true;
// Append the line to the text area
while (inLine != null)
{
if (firstLine)
{
firstLine = false;
jta.append(inLine);
}
else
{
jta.append("\n" + inLine);
}
inLine = infile.readLine();
}
}
catch (FileNotFoundException ex)
{
System.out.println("File not found: " + filename);
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
finally
{
try
{
if (infile != null) infile.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
}
展开