一些收藏

Java-I/O学习(6)

2020-04-04  本文已影响0人  Cool_Pomelo

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();



    }
}


上一篇下一篇

猜你喜欢

热点阅读