目录 文件名 java_列出某目录下Java文件名

更改第下面的样例程序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());

}

}

}

}

展开

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值