RandomAccessFile

package myc;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class TestFileDialog {
public static void main(String[] args) {
new FileFrame();
}
}
class FileFrame extends Frame implements ActionListener{

TextArea ta;
Button open,quit;
FileDialog fd;
FileFrame(){
super("获取并显示文本文件");
ta = new TextArea(10,45);
open = new Button("OPEN");
quit = new Button("CLOSE");
open.addActionListener(this);
quit.addActionListener(this);
setLayout(new FlowLayout());
add(ta);
add(open);
add(quit);
setSize(350,280);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="OPEN"){
fd = new FileDialog(this,"打开文件",FileDialog.LOAD);
fd.setDirectory("d:\\temp");//设置文本对话框的基础目录
fd.setVisible(true);//弹出文件对话框
try {
File myFile = new File(fd.getDirectory(),fd.getFile());
RandomAccessFile raf = new RandomAccessFile(myFile,"r");
while(raf.getFilePointer()<raf.length()){
ta.append(raf.readLine()+"\n");//读文件并加载到ta中
}
} catch (IOException e2) {
System.out.println(e2.toString());
}
}
if(e.getActionCommand()=="CLOSE"){
dispose();
System.exit(0);
}
}
}

你可能感兴趣的:(RandomAccessFile)