Java IO流-標准輸入輸出流


2017-11-05 19:13:21

標准輸入輸出流:System類中的兩個成員變量。

標准輸入流(public static final InputStream in):“標准”輸入流。此流已打開並准備提供輸入數據。通常,此流對應於鍵盤輸入或者由主機環境或用戶指定的另一個輸入源。

                      InputStream is = System.in;

標准輸出流(public static final PrintStream out):“標准”輸出流。此流已打開並准備接受輸出數據。通常,此流對應於顯示器輸出或者由主機環境或用戶指定的另一個輸出目標。

                      PrintStream ps = System.out;

  • System.out

標准輸出流本質是PrintStream類,下面來看一下PrintStream類的一些方法。

*常用方法

    public static void main(String[] args) {
        System.out.println("hello world.");
        
        //獲取標准輸出流對象
        PrintStream ps = System.out;
        ps.println("hello world");
    }

使用字符緩沖流進行包裝(很少用,因為不方便):

    public static void main(String[] args) throws IOException {
        BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(System.out));

        bw.write("hello");
        bw.newLine();
        bw.write("world");
        bw.newLine();
        bw.write("!");
        bw.flush();
        bw.close();

    }
  • System.in

標准輸入流本質是InputStream類。

鍵盤錄入的方法

    A:main方法接收參數

    B:Scanner類

      Scanner sc = new Scanner(System.in)

      int x = sc.nextInt()

    C:通過字符緩沖流包裝標准輸入流,BufferedReader類

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in))

 

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     // 讀到末尾返回null
        String line = br.readLine();
        int i = Integer.parseInt(line);
        System.out.println(i);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM