【JAVA IO】_列印流筆記

來源:互聯網
上載者:User

【JAVA IO】_列印流筆記

本章目標
掌握列印流的操作
掌握格式化輸出

列印流
在整個IO包中,列印流是輸出資訊最方便的類,主要包含位元組列印流(PrintStream)和字元列印流(printWriter)。列印流提供了非常方便的列印功能,可以列印任何的資料類型,例如:小數、整數、字串等等。

在這裡只介紹位元組列印流(PrintStream) ,因為字元列印流與位元組列印流相似,但是不常用。

回顧:之前在列印資訊的時候需要使用OutputStream,但是這樣一來,所有的資料輸出的時候非常的麻煩,String->byte[],列印流中可以方便的進行輸出。

在這個類中定義了很多的print()或println()方法。System.out.println(),此方法可以列印任何資料類型。

構造方法:
public PrintStream(OutputStream out)->指定輸出位置

此構造方法接收OutputStream的子類。

使用PrintStream輸出資訊。

import java.io.*;public class PrintDemo01{    public static void main(String[] args)throws Exception{        PrintStream ps = null;        ps = new PrintStream(new FileOutputStream(new File("d:"+File.separator+"test.txt")));        ps.print("hello");        ps.println("World!!");        ps.print("1+1="+2);        ps.close();    }}

也就是說此時,實際上是將FileOutputStream類的功能封裝了一下。這樣的設計在java中稱為裝飾設計。

格式化輸出

import java.io.*;public class PrintDemo02{    public static void main(String[] args)throws Exception{        PrintStream ps = null;    //聲明列印流對象        ps = new PrintStream(new FileOutputStream(new File("d:"+File.separator+"test.txt")));        String name = "牛兒吃草";        int age = 30;        float score = 990.356f;        char sex = 'M';        ps.printf("姓名:%s;年齡:%d;成績:%f;性別:%c",name,age,score,sex);        ps.close();    }}

簡化操作:

import java.io.*;public class PrintDemo03{    public static void main(String[] args)throws Exception{        PrintStream ps = null;    //聲明列印流對象        ps = new PrintStream(new FileOutputStream(new File("d:"+File.separator+"test.txt")));        String name = "牛兒吃草";        int age = 30;        float score = 990.356f;        char sex = 'M';        ps.printf("姓名:%s;年齡:%s;成績:%s;性別:%s",name,age,score,sex);        ps.close();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.