Java-I/O學習(6)

Java-I/O學習(6)

DataInputStream

DataInputStream可以讓你從InputStream讀取Java基本類型來代替原始的字節。用DataInputStream來包裝InputStream,你就可以從DataInputStream直接以Java基本類型來讀取數據。這就是爲什麼叫做DataInputStream

如果你需要讀取的數據是由大於一個字節的java基礎類型構成,比如int, long, float, double等,那麼用DataInputStream是很方便的。DataInputStream希望的數據是寫入到網絡的有序多字節數據。

創建


//Creates a DataInputStream that uses the specified underlying InputStream.
DataInputStream​(InputStream in)


read


//Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

//The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.

//The read(b) method has the same effect as:

    //read(b, 0, b.length)
final int read​(byte[] b)

//See the general contract of the readFully method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads some bytes from an input stream and stores them into the buffer array b. The number of bytes read is equal to the length of b.
final void readFully​(byte[] b)

//See the general contract of the readBoolean method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads one input byte and returns true if that byte is nonzero, false if that byte is zero. This method is suitable for reading the byte written by the writeBoolean method of interface DataOutput.
final boolean readBoolean()

//See the general contract of the readByte method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads and returns one input byte. The byte is treated as a signed value in the range -128 through 127, inclusive. This method is suitable for reading the byte written by the writeByte method of interface DataOutput.
final byte readByte()

//See the general contract of the readUnsignedByte method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads one input byte, zero-extends it to type int, and returns the result, which is therefore in the range 0 through 255. This method is suitable for reading the byte written by the writeByte method of interface DataOutput if the argument to writeByte was intended to be a value in the range 0 through 255.
final int readUnsignedByte()

//See the general contract of the readShort method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads two input bytes and returns a short value. Let a be the first byte read and b be the second byte. The value returned is:
        //(short)((a << 8) | (b & 0xff))
 //This method is suitable for reading the bytes written by the writeShort method of interface DataOutput.
final short readShort()

//See the general contract of the readChar method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads two input bytes and returns a char value. Let a be the first byte read and b be the second byte. The value returned is:
        //(char)((a << 8) | (b & 0xff))
//This method is suitable for reading bytes written by the writeChar method of interface DataOutput.
final char readChar()


//See the general contract of the readInt method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads two input bytes and returns a char value. Let a be the first byte read and b be the second byte. The value returned is:
        //(char)((a << 8) | (b & 0xff))
 //This method is suitable for reading bytes written by the writeChar method of interface DataOutput.
final int readInt()


//See the general contract of the readLong method of DataInput.
//Bytes for this operation are read from the contained input stream.

//from DataInput:
//Reads eight input bytes and returns a long value. Let a-h be the first through eighth bytes read. The value returned is:

//  (((long)(a & 0xff) << 56) |
//   ((long)(b & 0xff) << 48) |
//   ((long)(c & 0xff) << 40) |
//   ((long)(d & 0xff) << 32) |
//   ((long)(e & 0xff) << 24) |
//   ((long)(f & 0xff) << 16) |
//   ((long)(g & 0xff) <<  8) |
//   ((long)(h & 0xff)))
 
//This method is suitable for reading bytes written by the writeLong method of interface DataOutput.
final long readLong()

DataOutputStream

DataOutputStream可以讓你從OutputStream寫出Java基本類型來代替原始的字節。用DataOutputStream來包裝OutputStream,你就可以用DataOutputStream直接以Java基本類型來寫數據。這就是爲什麼叫做DataOutputStream。

結合使用:


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

        String pathName = "E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\k.txt";
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(pathName));
        dos.writeUTF("α");
        dos.writeInt(1234567);
        dos.writeBoolean(true);
        dos.writeShort((short)123);
        dos.writeLong((long)456);
        dos.writeDouble(99.98);
        DataInputStream dis = new DataInputStream(new FileInputStream(pathName));
        System.out.println(dis.readUTF());
        System.out.println(dis.readInt());
        System.out.println(dis.readBoolean());
        System.out.println(dis.readShort());
        System.out.println(dis.readLong());
        System.out.println(dis.readDouble());
        dis.close();
        dos.close();
        
    }

PrintStream

PrintStream繼承了FilterOutputStream.是"裝飾類"的一種,所以屬於字節流體系中(與PrintStream相似的流PrintWriter繼承於Writer,屬於字符流體系中),爲其他的輸出流添加功能.使它們能夠方便打印各種數據值的表示形式.與其他流不同的是,PrintStream流永遠不會拋出異常.因爲做了try{}catch(){}會將異常捕獲,出現異常情況會在內部設置標識,通過checkError()獲取此標識.PrintStream流有自動刷新機制,例如當向PrintStream流中寫入一個字節數組後自動調用flush()方法.

使用:


public class T4 {

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

        final String fileName = "E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\bb.txt";
        File file = new File(fileName);
        testPrintMethod(fileName, file);
        testOtherMethod(fileName,file);
    }


    private static void testOtherMethod(String fileName,File file) throws IOException {
        PrintStream ps = new PrintStream(fileName);
        ps.write("helloworld".getBytes());
        ps.println();
        ps.format("文件名稱:%s", file.getName());
        ps.println();
        ps.write(0x41);
        ps.append("abcde");
        ps.close();

    }

    private static void testPrintMethod(final String fileName, File file) throws FileNotFoundException {
        PrintStream ps = new PrintStream(new FileOutputStream(fileName));
        ps.println('a');
        ps.println("hello");
        ps.println(2345);
        ps.print(3.1415);
        ps.println();//寫入換行符.
        ps.printf("文件名稱:%s,是否可讀:%s", file.getName(),file.canRead());
        ps.println();
        ps.close();
    }

}

ObjectInputStream & ObjectOutputStream

ObjectInputStream(java.io.ObjectInputStream)可以從InputStream讀取Java對象來代替原始的字節。用ObjectInputStream來包裝InputStream然後就可以從它裏面直接讀取對象。當然,讀取的字節必須是有效且可序列化的Java對象,否則就會讀取失敗。
一般情況下你會用ObjectInputStream讀取對象,用ObjectOutputStream寫對象(序列化)。稍後會給出相關的例子。


public class Student implements Serializable {

    private static final long serialVersionUID = -187877186941003078L;
    String name;
    int id;
    transient int age;   // transient   瞬時的,不持久化. 此處若把transient加上,就可以單獨不對age進行持久化操作transient int age

    String department;

    public Student(String name, int id, int age, String department) {
        this.age = age;
        this.department = department;
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", id=" + id + ", age=" + age
                + ", department=" + department + "]";
    }


}


public class Seri {

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

        String path = "E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\Blog\\A7\\D\\test.txt";

        Student s1 = new Student("張三", 1, 20, "數據結構");
        Student s2 = new Student("李四", 2, 19, "網絡");

        List<Student> list=new ArrayList<Student>();
        list.add( s1);
        list.add(s2);

		/*ObjectOutputStream 和 ObjectInputStream 分別與 FileOutputStream 和
		FileInputStream 一起使用時,可以爲應用程序提供對對象圖形的持久存儲。*/

        // 將學生信息封裝到student.txt中
        // 創建一個向 student.txt 的文件中寫入數據的文件輸出流。
        FileOutputStream fout = new FileOutputStream(path);

        //ObjectOutputStream 將 Java 對象的基本數據類型和圖形寫入 OutputStream。可以使用 ObjectInputStream 讀取(重構)對象。
        ObjectOutputStream out = new ObjectOutputStream(fout);

        //writeObject 方法負責寫入特定類的對象狀態,以便相應的 readObject 方法可以恢復它。
        out.writeObject(list);


        //FileInputStream 類從文件系統中的一個文件中獲取輸入字節。
        FileInputStream fin = new FileInputStream(path);
        //創建從指定 InputStream 讀取的 ObjectInputStream。從流讀取序列化頭部並予以驗證。
        ObjectInputStream in = new ObjectInputStream(fin);

        // 捕獲異常
        try {
			/* readObject 方法爲類重寫默認的反序列化
			readObject 方法用於從流讀取對象。應該使用 Java 的安全強制轉換來獲取所需的類型。
			在 Java 中,字符串和數組都是對象,所以在序列化期間將其視爲對象。讀取時,需要將其強制轉換爲期望的類型。*/
            List<Student> l= (List<Student>) in.readObject();
            for(  Student s: l){
                System.out.println(   s );
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 關閉流
        out.close();
        in.close();



    }
}


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