:
代码示例如下:
public class BWF implements ActionListener{
JFrame f=null;
JLabel label=null;
JTextArea textArea=null;
JFileChooser fileChooser;
public BWF() {
f=new JFrame("");
Container contentPane=f.getContentPane();
textArea=new JTextArea();
JScrollPane scrollPane=new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(350, 300));
JPanel panel=new JPanel();
JButton b1=new JButton("新建文件");
b1.addActionListener(this);
JButton b2=new JButton("退出文件");
b2.addActionListener(this);
panel.add(b1);
panel.add(b2);
label=new JLabel("",JLabel.CENTER);
//建立一个FileChooser对象,指定D盘目录为默认文件对话框路径
fileChooser=new JFileChooser("D:\\");
contentPane.add(label,BorderLayout.NORTH);
contentPane.add(scrollPane,BorderLayout.CENTER);
contentPane.add(panel,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new BWF();
}
public void actionPerformed(ActionEvent e) {
File file=null;
int result;
if(e.getActionCommand().equals("新建文件")){
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("打开文件");
result=fileChooser.showOpenDialog(f);
textArea.setText("");
if(result==JFileChooser.APPROVE_OPTION){
file=fileChooser.getSelectedFile();
label.setText("你打开的文件名为:"+file.getName());
}
else if(result==JFileChooser.CANCEL_OPTION){
label.setText("你没有选择任何文件");
}
FileInputStream fileInputStream=null;
if(file!=null){
try{
fileInputStream=new FileInputStream(file);
}catch(Exception e1){
label.setText("没找到文件");
return;
}
String readbyte=null;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));
while((readbyte=br.readLine())!=null){
textArea.setLineWrap(true);
textArea.append(String.valueOf(readbyte));
}
}catch(Exception e1){
label.setText("读取文件错误");
}finally {
try{
if(fileInputStream!=null){
fileInputStream.close();
}
}catch(Exception e1){
}
}
}
}
}
}