實例1:
package dataInputStreamAndPrintStreamDemo; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.PrintStream; //示範如何自鍵盤讀入字符串,並使用DataInputStream,PrintStream類將程序執行顯示在屏幕(標準輸出)上public class DataInputStreamAndPrintStreamDemo { public static void main(String[] args) { int count; byte input[] = new byte[256]; String InputString; // 鍵盤讀入DataInputStream stdin = new DataInputStream(System.in); //提高執行效率,幾乎所有的InputStream類都可以被BufferedStream類包覆(wrap)來提高I/O效率BufferedInputStream bufin = new BufferedInputStream(stdin); // 屏幕輸出DataOutputStream stdout = new DataOutputStream(System.out);// 將結果輸出至屏幕BufferedOutputStream bufout = new BufferedOutputStream(stdout);// 提高輸出效率PrintStream p = new PrintStream(System.out);// 將結果輸出至屏幕try { if (bufin.markSupported()) { p.println("支持串流標記:是");// 使用PrintStream輸出p.println("輸入字符串,結束請按【Enter】.../n" + "=>"); //使得流在第一個位被作上標記(mark),並且會保留256位(mark(256)) bufin.mark(256); //讀取字節並存放在指定的數組中count = bufin.read(input); p.println("讀入字符數:" + count); p.print("你輸入的字符串為:"); // 寫入流,只是將數據寫入流中而已,並不輸出數據// 所以在其後必須使用flush()函數將流中的數據強制輸出bufout.write(input, 0, count); bufout.flush();// 強制輸出至指定的輸出裝置bufin.reset();// 將讀取位置移至標記處,也就是流中的第一位bufin.read(input, 0, count); p.print("字符串的前半段:"); bufout.write(input, 0, count / 2); //相當於System.out.println(); bufout.write((int)('/n')); bufout.flush(); bufin.reset(); bufin.skip(count / 2); bufin.read(input, 0, count / 2); p.print("字符串的後半段:"); bufout.write(input, 0, count / 2); bufout.flush(); } else { System.out.println("字符串流標記:否"); } // 關閉流p.close(); stdin.close(); bufin.close(); stdout.close(); bufout.close(); } catch (IOException E) { System.out.println("發生I/O錯誤!!!"); } } } //其實我們對PrintStream類應該很熟悉才對,System.out就是一個PrintStream類對象,其提供的print()和println()函數//幾乎可顯示所有數據類型的變量//例程2:package iotest; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.logging.Level; import java.util.logging.Logger; public class IOtest { public static void main(String[] args) throws IOException { byte buf[] = new byte[255]; byte bufin[] = new byte[255]; //只能用byte格式將數據送入文件String str = "輸入的文字:"; buf = str.getBytes(); try { FileOutputStream fout = new FileOutputStream("test.txt"); PrintStream p = new PrintStream(fout); p.println("輸入的文字~~~~~~~"+'/n'); //方式一fout.write(buf, 0, buf.length); //方式二fout.write(buf); //方式三//fout.flush(); //fout.close(); System.out.println("快輸入文字:"); int bytes = System.in.read(bufin, 0, 255); //追加文本!!!!!!!!!!!!!!!! //fout = new FileOutputStream("test.txt",true); fout.write(bufin, 0, bytes); } catch (FileNotFoundException ex) { Logger.getLogger(IOtest.class.getName()).log(Level.SEVERE, null, ex); } } }結果:
//輸入的文字~~~~~~~ //輸入的文字:輸入的文字:宸ヤfdsfdssssssssssssssssssssssssssss
總結
以上就是本文關於Java流操作之數據流實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!