Java的三種簡單的控制檯輸入和輸出方式

    //控制檯輸出
    public static void ScannerInputAndOut(){
        Scanner in = new Scanner(System.in);
        System.out.println(in.nextLine());
    }
    /**
     * 字節流
     */
    public static void ByteInputAndOut(){
        //輸入
        BufferedInputStream in = new BufferedInputStream(System.in);
        try {
            byte[] b = new byte[1024];
            in.read(b);
            System.out.println(new String(b));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //輸出
        BufferedOutputStream out = new BufferedOutputStream(System.out);
        try {
            for (int i = 0; i < 5; i++) {
                out.write("hello".getBytes());
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符流
     */
    public static void CharInputAndOut(){
        //輸入
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println(in.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //輸出
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
        try {
            for (int i = 0; i < 5; i++) {
                out.write("hello"+i);
                out.newLine();
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

發佈了141 篇原創文章 · 獲贊 36 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章