usertest.java

来自「java 完全探索的随书源码」· Java 代码 · 共 51 行

JAVA
51
字号
import java.io.*;public class UserTest{  // Constant for the user data file name  public static final String USER_DATA_FILE = "users.dat";  public static void main(String[] args)  {    // Create a couple of User objects    User user1 = new User( "User1", "foobar" );    User user2 = new User( "admin", "admin" );    User user3 = new User( "guest", "guest" );    try    {      // Create the streams to write the objects out      // Notice there is really no difference here. The real      // difference is in the User class      FileOutputStream out = new FileOutputStream( USER_DATA_FILE );      ObjectOutputStream objOutStr = new ObjectOutputStream( out );      objOutStr.writeObject( user1 );      objOutStr.writeObject( user2 );      objOutStr.writeObject( user3 );      // Read the users back in      FileInputStream in = new FileInputStream( USER_DATA_FILE );      ObjectInputStream objInStr = new ObjectInputStream( in );      // Print all of the User's out      while( true )      {        System.out.println( objInStr.readObject() );      }    }    catch( EOFException ex )    {      System.out.println( "All records have been read" );    }    catch( FileNotFoundException ex )    {      System.out.println( "Could not find the file " + USER_DATA_FILE );    }    catch( IOException ex )    {      System.out.println( "There was a problem with serialization of the users" );    }    catch( ClassNotFoundException ex )    {      System.out.println( "Could not find the User class definition" );    }  }}

⌨️ 快捷键说明

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