输入流输出流实现文本读取
在窗体中通过按钮控制,读取文档中的文本,在窗体中显示。
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
public class Stream extends JFrame implements ActionListener {
JFrame f;
TextArea ta;
JButton btn;
FileDialog fd;
File file1 = null;
public Stream() {
btn = new JButton("查看");
ta = new TextArea(20, 25);
btn.addActionListener(this);
}
@Override
public void show() {
f = new JFrame("公司信息");
f.setSize(300, 450);
f.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
f.add(btn);
f.add(ta);
// 添加指定的窗口焦点侦听器,以从此窗口接收窗口事件
f.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent evt) {
f.setVisible(false); // 设置是否可见
f.dispose();
}
});
f.setLocation(200, 200);
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == btn) {
fd = new FileDialog(f,"OPEN",FileDialog.LOAD); // 显示一个对话框窗口
fd.setVisible(false);
}
try {
file1 = new File("D:\\1913040150\\java期末大作业\\src\\PlatformInformation\\信息介绍"); // 文档位置,最好是直接在java project下创建文本文档
FileReader fr = new FileReader(file1); // 文件输入流
BufferedReader br = new BufferedReader(fr); // 字节输入流
String aline;
while ((aline=br.readLine()) != null) {
ta.append(aline + "\r\n");
}
fr.close();
br.close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public static void main(String[] args) {
Stream m = new Stream();
m.show();
}
}