在这个例子中,我们使用了Java中的awt包来实现可视化的功能,然后可以把一个文件的内容显示出来。里面用到了IO的知识,还有可视化的一些内容。这个例子,我们只要想说的就是IO部分,至于可视化,不是重点。
package chapter03;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileViewer extends Frame implements ActionListener{
String directory;
TextArea textarea;
public FileViewer(){
this(null,null);
}
public FileViewer(String directory,String filename){
super();
//添加窗体关闭事件
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
textarea=new TextArea("",24,80);
textarea.setFont(new Font("MonoSpaced",Font.PLAIN,12));
textarea.setEditable(false);
this.add("Center",textarea);
Panel p=new Panel();
p.setLayout(new FlowLayout(FlowLayout.RIGHT,10,5));
this.add(p,"South");
Font font=new Font("SansSerif",Font.BOLD,14);
Button openfile=new Button("open file");
Button close=new Button("close");
openfile.addActionListener(this);
openfile.setActionCommand("open");
openfile.setFont(font);
close.addActionListener(this);
close.setActionCommand("close");
close.setFont(font);
p.add(openfile);
p.add(close);
this.pack();
if(directory==null){
File f;
if((filename!=null) && (f=new File(filename)).isAbsolute()){
directory=f.getParent();
filename=f.getName();
}else{
directory=System.getProperty("user.dir");
}
}
this.directory=directory;
setFile(directory,filename);
}
public void setFile(String directory,String filename){
if((filename==null)|| (filename.length()==0)){
return ;
}
File f;
FileReader in=null;
try{
f=new File(directory,filename);
in=new FileReader(f);
//定义一个数组
char [] buffer=new char[4096];
int len;
textarea.setText(" ");
//读取文件
while((len=in.read(buffer))!=-1){
//System.out.println(len);
String msg=new String(buffer,0,len);
//将读取出来的内容添加到窗体上
textarea.setText(msg);
}
this.setTitle("FileViewer: "+filename);
textarea.setCaretPosition(0);
}catch(IOException e){
textarea.setText(e.getClass().getName()+" : "+e.getMessage());
this.setTitle("FileViewer :"+filename+" :I/O Exception");
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void actionPerformed(ActionEvent e) {
String cmd=e.getActionCommand();
if(cmd.equals("open")){
FileDialog f=new FileDialog(this,"Open File",FileDialog.LOAD);
f.setDirectory(directory);
f.setVisible(true);
directory=f.getDirectory();
setFile(directory,f.getFile());
f.dispose();
}else if(cmd.equals("close")){
System.exit(0);
}
}
public static void main(String [] args)throws IOException{
FileViewer f=new FileViewer("e:\\java\\","Hello.java");
f.setVisible(true);
}
}