1. 程式人生 > 其它 >Java-IO流系列-標準輸入輸出流

Java-IO流系列-標準輸入輸出流

標準輸入輸出流

什麼是標準輸入輸出流

  • System.in和System.out分別代表了系統標準的輸入和輸出裝置,System還包括了err這個屬性
  • 預設輸入裝置是:鍵盤,輸出裝置是:顯示器
  • System.in的型別是InputStream
  • System.out的型別是PrintStream,其是OutputStream的子類
  • FilterOutputStream的子類
  • System類的setIn(InputStream is) / setout(PrintStream is)方式重新指定輸入和輸出的流。

練習

從鍵盤輸入字串,要求將讀取到的整行字串轉成大寫輸出。然後繼續進行輸入操作,
直至當輸入“e”或者“exit"時,退出程式。

使用System. in實現。System. in--->轉換流 --->BufferedReader 的readline()

package com.dreamcold.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Demo14 {
    public static void main(String[] args) {
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        while (true){
            System.out.println("請輸入字串:");
            String data=null;
            try {
                data=br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (data.equalsIgnoreCase("e")||data.equalsIgnoreCase("exit")){
                System.out.println("程式結束了");
                break;
            }
            String upper=data.toUpperCase();
            System.out.println(upper);
        }
    }
}

效果:

除此之外還可以用使用Scanner實現,呼叫next()返回一個字串實現

列印流

  • 實現將基本資料型別的資料格式轉化為字串輸出

  • 列印流: PrintStream和PrintWriter

    • 提供了一系列過載的print()和println()方法,用於多種資料型別的輸出
    • PrintStream和PrintWriter的輸出不會丟擲IOException異常
    • PrintStream和PrintWriter有自動flush功能
    • PrintStream列印的所有字元都使用平臺的預設字元編碼轉換為位元組。
    • 在需要寫入字元而不是寫入位元組的情況下,應該使用PrintWriter類。
    • System.out返回的是PrintStream的例項
  • 提供了一系列過載的print()和println()

package com.dreamcold.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Demo15 {
    public static void main(String[] args) {
        PrintStream ps=null;
        try {
            FileOutputStream fos=new FileOutputStream("output.txt");
            //建立列印輸出流,設定為自動重新整理的模式,吸入換行符或者位元組'\n,的時候都會重新整理輸出的緩衝區
            ps=new PrintStream(fos,true);
            if (ps!=null){
               System.setOut(ps);
            }
            for (int i=0;i<=255;i++){
                System.out.println((char)i);
                if (i%50==0){
                    System.out.println();
                }
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }finally {
            if (ps!=null){
                ps.close();
            }
        }
    }
}

效果: