Java: accessing a List of Strings as an InputStream

前端 未结 7 1549
情深已故
情深已故 2021-02-05 11:24

Is there any way InputStream wrapping a list of UTF-8 String? I\'d like to do something like:

InputStream in = new XyzInputStream( List         


        
7条回答
  •  无人及你
    2021-02-05 11:58

    you can also do this way create a Serializable List

    List quarks = Arrays.asList(
          "up", "down", "strange", "charm", "top", "bottom"
        );
    
    //serialize the List
    //note the use of abstract base class references
    
    try{
      //use buffering
      OutputStream file = new FileOutputStream( "quarks.ser" );
      OutputStream buffer = new BufferedOutputStream( file );
      ObjectOutput output = new ObjectOutputStream( buffer );
      try{
        output.writeObject(quarks);
      }
      finally{
        output.close();
      }
    }  
    catch(IOException ex){
      fLogger.log(Level.SEVERE, "Cannot perform output.", ex);
    }
    
    //deserialize the quarks.ser file
    //note the use of abstract base class references
    
    try{
      //use buffering
      InputStream file = new FileInputStream( "quarks.ser" );
      InputStream buffer = new BufferedInputStream( file );
      ObjectInput input = new ObjectInputStream ( buffer );
      try{
        //deserialize the List
        List recoveredQuarks = (List)input.readObject();
        //display its data
        for(String quark: recoveredQuarks){
          System.out.println("Recovered Quark: " + quark);
        }
      }
      finally{
        input.close();
      }
    }
    catch(ClassNotFoundException ex){
      fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
    }
    catch(IOException ex){
      fLogger.log(Level.SEVERE, "Cannot perform input.", ex);
    }
    

提交回复
热议问题