⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 example8_10.java

📁 书中的例题
💻 JAVA
字号:
/* 对象流的应用 */
import java.awt.*;
import java.awt.event.*;
import java.io.*;
 class ObjectRW extends Frame implements ActionListener
 { 
   TextArea             text=null;
   FileInputStream      file_in=null;
   FileOutputStream     file_out=null;
   ObjectInputStream    object_in=null;     //对象输入流。
   ObjectOutputStream   object_out=null;    //对象输出流。
   Button btn_读出=null,btn_写入=null;
   ObjectRW()
   { 
	  setSize(300,150);	 
	  setLayout(new FlowLayout());
	  text=new TextArea(6,12);
      btn_读出=new Button("读取对象");
	  btn_写入=new Button("写入文件");
      btn_读出.addActionListener(this);
	  btn_写入.addActionListener(this);
      setVisible(true);
	  Panel p=new Panel();
	  add(text);add(p);
	  p.setLayout(new GridLayout(2,1));
	  p.add(btn_写入);p.add(btn_读出);
      btn_读出.setEnabled(false);
      addWindowListener(new WindowAdapter()
         {  public void windowClosing(WindowEvent e)
              {  System.exit(0);     }
          });
      validate();

   }
   public void actionPerformed(ActionEvent e)
   {
	 if(e.getSource()==btn_写入)
      {
	    try{
			file_out=new FileOutputStream("a.dat");
            //创建对象输出流。
			object_out=new ObjectOutputStream(file_out);
            //将文本区对象写到文件中。
			object_out.writeObject(text);                
            object_out.close();
			btn_读出.setEnabled(true);
			this.validate();
           }
         catch(IOException event){System.out.println(event);}
          }
     else if(e.getSource()==btn_读出)
       {
		 try{
			 file_in=new FileInputStream("a.dat");
             //创建对象输入流。
			 object_in=new ObjectInputStream(file_in);    
             //从文件中读入对象。
			 TextArea temp=(TextArea)object_in.readObject();
			 temp.setBackground(Color.pink);
			 //添加该对象到窗口。
			 this.add(temp);
             this.pack();this.setSize(300,150);
             object_in.close();
             }
         catch(ClassNotFoundException event)
             {  System.out.println("不能读出对象"); }
         catch(IOException event)
               {  System.out.println("can not read file");
               }
       }
   }
}
//主类
 public class Example8_10
  {
    public static void main(String[] args) 
 	 { new ObjectRW();	}
  }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -