天天看點

列印流和資料流

列印流:位元組流 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();
            }
        }
    }
}      
@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();
            }
        }
    }
}      

繼續閱讀