日期:2014-05-20 浏览次数:20900 次
/*例9.3(P179) 说明BufferedWriter类用法的应用程序*/
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MyWindow extends JFrame implements ActionListener
{
JTextArea text; JButton button;
FileWriter writefile; BufferedWriter out;
MyWindow()
{
super("缓冲式样流的输出");
Container con=this.getContentPane();//获得内容面板
text=new JTextArea(20,30); text.setBackground(Color.cyan);
button=new JButton("写文件"); button.addActionListener(this);
con.setLayout(new BorderLayout());
con.setSize(40,40);
con.setVisible(true);
con.add(text,"Center");
con.add(button, "South");
try
{
writefile=new FileWriter("d:\\file2.txt");
out=new BufferedWriter(writefile);
}
catch(IOException e) {}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button) //将文本区内容采用缓冲式输出到文件
{try {
out.write(text.getText(),0,(text.getText()).length());
out.flush();
text.setText(null);
System.exit(0);
}
catch (IOException exp)
{
text.setText("文件写出错!\n");
System.exit(-1);
}
}
}
}
public class Test
{
public static void main(String args[])
{
MyWindow myWin=new MyWindow();
myWin.pack();
}
}
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MyWindow extends JFrame implements ActionListener
{
static final long serialVersionUID=1L;
JTextArea text; JButton button;
FileWriter writefile; BufferedWriter out;
MyWindow()
{
super("缓冲式样流的输出");
Container con=this.getContentPane();//获得内容面板
text=new JTextArea(20,30);
text.setBackground(Color.cyan);
button=new JButton("写文件");
button.addActionListener(this);
con.setLayout(new BorderLayout());
con.setSize(40,40);
con.setVisible(true);
con.add(text,"Center");
con.add(button, "South");
try
{
writefile=new FileWriter("d:\\file2.txt");
out=new BufferedWriter(writefile);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button) //将文本区内容采用缓冲式输出到文件
{try {
out.write(text.getText(),0,(text.getText()).length());
out.flush();
text.setText(null);
System.exit(0);
}
catch (IOException exp)
{
text.setText("文件写出错!\n");
System.exit(-1);
}
}
}
}
public class Test2
{
public static void main(String args[])
{
MyWindow myWin=new MyWindow();
myWin.pack();
myWin.setVisible(true);
myWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}