欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Binary IO

程序员文章站 2022-07-13 12:28:42
...

FileInputStream

  • 2 Constructors
    • public FileInputStream ( String filename)
    • public FileInputStream ( File file)

FileOutputStream

  • 4 Constructors
    • public FileOutputStream ( String filename)
    • public FileOutputStream ( File file)
    • public FileOutputStream ( String filename, Boolean append)
    • public FileOutputStream ( File file, Boolean append)

DataInputStream

  • Constructor
    public DataInputStream ( InputStream instream)
  • Example:
    DataInputStream infile = new DataInputStream ( new FileInputStream ( "in.dat" ) ) ;
    infile.readBoolean ( ) ;
    infile.readByte ( ) ;
    infile.readBytes ( ) ;    // Read lower byte of characters
    infile.readChar ( ) ;
    infile.readChars ( ) ;    // Read every character
    infile.readFloat ( ) ;
    infile.readDouble ( ) ;
    infile.readInt ( ) ;

    ...

DataOutputStream

  • Constructor
    public DataOutputStream ( OutputStream outstream)
  • Example:
    DataOutputStream outfile = new DataOutputStream ( new FileOutputStream ( "out.dat" ) ) ;
    outfile.writeBoolean ( boolTmp) ;
    outfile.writeByte ( intTmp) ;
    outfile.writeBytes ( strTmp) ;    // Write lower byte of characters
    outfile.writeChar ( charTmp) ;
    outfile.writeChars ( strTmp) ;    // Write every character
    outfile.writeFloat ( floatTmp) ;
    outfile.writeDouble ( dblTmp) ;
    outfile.writeInt ( intTmp) ;

    ...

BufferedInputStream/ BufferedOutputStream

  • Using buffers to speed up I/O
  • Constructor
    public BufferedInputStream ( InputStream in)
    public BufferedInputStream ( InputStream in, int bufferSize)
  • Constructor
    public BufferedOutputStream ( OutputStream out)
    public BufferedOutputStream ( OutputStreamr out, int bufferSize)

ObjectInputStream/ ObjectOutputStream

  • Enables to perform I/O for
  • Constructor
    public ObjectInputStream ( InputStream in)
  • Constructor
    public ObjectOutputStream ( OutputStream out)

RandomAccessFile

  • to allow a file to be read from and write to at random locations
  • Constructor
    // Allow read and write
    RandomAccessFile raf = new RandomAccessFile ( "test.dat" , "rw" ) ;
    // Read only
    RandomAccessFile raf = new RandomAccessFile ( "test.dat" , "r" ) ;
  • Example
    RandomAccessFile inout = new RandomAccessFile ( "test.dat" , "rw" ) ;

    // Clear the file to destroy the old contents if exists
    inout.setLength ( 0 ) ;
    // Write new integers to the file
    for ( int i = 0 ; i < 200 ; i++ )
        inout.writeInt ( i) ;
    System .out .println ( inout.length ( ) ) ; // length of the file
    inout.seek ( 0 ) ; // Move the file pointer to the beginning
    System .out .println ( inout.readInt ( ) ) ;
    inout.seek ( 1 * 4 ) ; // Move the file pointer to the 2nd number
    System .out .println ( inout.readInt ( ) ) ;
    // Close file
    inout.close ( ) ;