打印流和数据流

打印流:字节流 PrintStream 字符流: PrintWriter

@Test
public void printStreamWriter(){
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(new File("print.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    //创建打印输出流,设置为自动刷新模式写入换行符或字节'\n'时,都会刷新输出缓冲区)
    PrintStream ps = new PrintStream(fos, true);
    if (ps!=null){
        //把标准输出流(控制台输出)改成文件
        System.setOut(ps);
    }
    for (int i = 0; i <= 255; i++) {
    //这里要设置
    System.out.print((char) i);
    if (i % 50 ==0){
        System.out.println();
    }
    }
    ps.close();
}

数据流的使用 DataInputStream和DataOutputStream

DataOutputStream

//数据流
//DataInputStream 和 DataOutputStream
//boolean readBoolean()       byte readByte()
//char readChar()        float readFloat()
//double readDouble()     short readShort()
//long readLong()        int readInt()
//String readUTF()字符串    void readFully(byte[] b) 字节数组

@Test
public void testData(){
    DataOutputStream dos = null;
    try {
        FileOutputStream fos = new FileOutputStream("data.txt");
         dos = new DataOutputStream(fos);

        dos.writeUTF("加油!努力就会有未来!");
        dos.writeBoolean(true);
        dos.writeLong(313423432);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (dos !=null){
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

DataInputStream

@Test
public void testData1(){
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new FileInputStream(new File("data.txt")));
        byte[] b = new byte[20];
        int len;
        //while ((len = dis.read(b)) != -1){
        //    System.out.println(new String(b,0,len));
        //} 读取是错误的
        String str = dis.readUTF();
        System.out.println(str);
        boolean b1 = dis.readBoolean();
        System.out.println(b1);

        long l = dis.readLong();
        System.out.println(l);

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (dis != null){
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/wwwzydcom/article/details/85054977