Java数据流DataInputStream和DataOutputStream代码实例

package IO;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 *数据流
 * 与机器无关的操作JAVA基本数据类型
 *
 */
public class DataStreamDemo {
    public static void main(String[] args) {
        write();
        read();

    }
    public static void read(){
        File file = new File("c://test/hh.dat");
        try {
            FileInputStream inputStream = new FileInputStream(file);
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            int i=dataInputStream.readInt();//按照写的顺序依次读出
            byte j=dataInputStream.readByte();
            String k=dataInputStream.readUTF();
            System.out.println("i="+i+" j="+j+" k="+k);
            dataInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void write(){
        File file = new File("c://test/hh.dat");
        try {
            OutputStream outputStream = new FileOutputStream(file);
            DataOutputStream dos = new DataOutputStream(outputStream);
            dos.writeInt(10);//写入四个字节
            dos.writeByte(1);//写入1个字节
            dos.writeUTF("中");

            dos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(java,java)