Java-I/O學習(3)

Java-I/O學習(3)

RandomAccessFile

構造函數

構造方法 具體描述
RandomAccessFile​(File file, String mode) Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
RandomAccessFile​(String name, String mode) Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

讀取方法

返回類型 方法 具體描述
int read() Reads a byte of data from this file.
int read​(byte[] b) Reads up to b.length bytes of data from this file into an array of bytes.
int read​(byte[] b, int off, int len) Reads up to len bytes of data from this file into an array of bytes.
boolean readBoolean() Reads a boolean from this file.
byte readByte() Reads a signed eight-bit value from this file.
char readChar() Reads a character from this file.
double readDouble() Reads a double from this file.
float readFloat() Reads a float from this file.
void readFully​(byte[] b) Reads b.length bytes from this file into the byte array, starting at the current file pointer.
void readFully​(byte[] b, int off, int len) Reads exactly len bytes from this file into the byte array, starting at the current file pointer.
int readInt() Reads a signed 32-bit integer from this file.
String readLine() Reads the next line of text from this file.
long readLong() Reads a signed 64-bit integer from this file.
short readShort() Reads a signed 16-bit number from this file.
int readUnsignedByte() Reads an unsigned eight-bit number from this file.
int readUnsignedShort() Reads an unsigned 16-bit number from this file.
String readUTF() Reads in a string from this file.

寫入方法

返回類型 方法 具體描述
void write​(byte[] b) Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
void write​(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this file.
void write​(int b) Writes the specified byte to this file.
void writeBoolean​(boolean v) Writes a boolean to the file as a one-byte value.
void writeByte​(int v) Writes a byte to the file as a one-byte value.
void writeBytes​(String s) Writes the string to the file as a sequence of bytes.
void writeChar​(int v) Writes a char to the file as a two-byte value, high byte first.
void writeChars​(String s) Writes a string to the file as a sequence of characters.
void writeDouble​(double v) Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.
void writeFloat​(float v) Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.
void writeInt​(int v) Writes an int to the file as four bytes, high byte first.
void writeLong​(long v) Writes a long to the file as eight bytes, high byte first.
void writeShort​(int v) Writes a short to the file as two bytes, high byte first.
void writeUTF​(String str) Writes a string to the file using modified UTF-8 encoding in a machine-independent manner.

其餘方法

返回類型 方法 具體描述
void close() Closes this random access file stream and releases any system resources associated with the stream.
FileChannel getChannel() Returns the unique FileChannel object associated with this file.
FileDescriptor getFD() Returns the opaque file descriptor object associated with this stream.
long getFilePointer() Returns the current offset in this file.
long length() Returns the length of this file.
void seek​(long pos) Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
void setLength​(long newLength) Sets the length of this file.
int skipBytes​(int n) Attempts to skip over n bytes of input discarding the skipped bytes.

使用RandomAccessFile可以讓你在文件中來回移動進行來讀寫操作,也可以覆蓋文件中的某部分內容。這是FileInputStream和FileOutputStream做不到的。

創建


/**
* @exception  IllegalArgumentException  if the mode argument is not equal
*               to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
*               <tt>"rwd"</tt>
* @exception FileNotFoundException
*            if the mode is <tt>"r"</tt> but the given string does not
*            denote an existing regular file, or if the mode begins with
*            <tt>"rw"</tt> but the given string does not denote an
*            existing, writable regular file and a new regular file of
*            that name cannot be created, or if some other error occurs
*            while opening or creating the file
*/
RandomAccessFile(String name, String mode)

mode參數在API文檔中的說明:

The mode argument specifies the access mode in which the file is to be opened. The permitted values and their meanings are:

Value Meaning
“r” Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown.
“rw” Open for reading and writing. If the file does not already exist then an attempt will be made to create it.
“rws” Open for reading and writing, as with “rw”, and also require that every update to the file’s content or metadata be written synchronously to the underlying storage device.
“rwd” Open for reading and writing, as with “rw”, and also require that every update to the file’s content be written synchronously to the underlying storage device.

RandomAccessFile accessFile = new RandomAccessFil("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\d.txt","r");


read


// Reads a byte of data from this file. The byte is returned as an integer in the range 0 to 255 (0x00-0x0ff). This method blocks if no input is yet available.

// Although RandomAccessFile is not a subclass of InputStream, this method behaves in exactly the same way as the InputStream.read() method of InputStream.

read()

 public static void main(String[] args) throws IOException {

        RandomAccessFile accessFile = new RandomAccessFile("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\d.txt","r");

        int data = accessFile.read();

        while (data != -1) {

//            System.out.println((char) data);

            data = accessFile.read();

        }

        accessFile.close();


    }


// Although RandomAccessFile is not a subclass of InputStream, this method behaves in exactly the same way as the InputStream.read(byte[], int, int) method of InputStream.


read​(byte[] b,
                int off,
                int len)

  public static void main(String[] args) throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\d.txt","r");

        byte[] bytes = new byte[1024];

        int data = accessFile.read(bytes);

        while (data != -1) {

            data = accessFile.read(bytes);

        }

        accessFile.close();

    }


// Reads exactly len bytes from this file into the byte array, starting at the current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown.


readFully​(byte[] b,int off,int len)



    public static void main(String[] args) throws IOException {

        RandomAccessFile accessFile = new RandomAccessFile("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\d.txt","r");

        byte[] bytes = new byte[1024];
        
        accessFile.readFully(bytes);
        
        accessFile.close();
    }



write


// Writes the specified byte to this file. The write starts at the current file pointer.
write​(int b)


// Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
write​(byte[] b)

    public static void main(String[] args) throws IOException {

        RandomAccessFile accessFile = new RandomAccessFile("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\f.txt","rw");

//        accessFile.write(122);
//
//        System.out.println("-------------");
//
//        accessFile.write("abcdfgh123".getBytes());
//
//        System.out.println("-------------");

//        accessFile.writeBoolean(true);

        accessFile.writeByte(121);

        accessFile.writeBytes("Hello world");

        accessFile.close();


    }
}

其餘操作


// Returns:
// the length of this file, measured in bytes.
length()

// Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change the file length. The file length will change only by writing after the offset has been set beyond the end of the file.
seek​(long pos)

// Attempts to skip over n bytes of input discarding the skipped bytes.
// This method may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. This method never throws an EOFException. The actual number of bytes skipped is returned. If n is negative, no bytes are skipped.
skipBytes​(int n)

   public static void main(String[] args) throws IOException {

        RandomAccessFile accessFile = new RandomAccessFile("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\f.txt", "rw");

//        System.out.println(accessFile.length());//

//        System.out.println(accessFile.getFilePointer());


        //從下表 5(包括) 的位置開始讀取
//        accessFile.seek(5);
//

        accessFile.skipBytes(5);

        int data = accessFile.read();

        while (data != -1) {
            System.out.println((char) data);

            data = accessFile.read();
        }
        accessFile.close();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章