標籤:java 位元組流
/*位元組流InputStreamOutputStream 位元組流緩衝區BufferedInputStreamBufferedOutputStreamSystem.out:對應的是標準輸出裝置,控制台System.in:對應的標準輸入裝置,鍵盤InputStreamReader:字元流轉換為位元組流,位元組流及其緩衝沒有readLine方法,先變為字元流緩衝區*/package pack;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class Main { public static void sys(Object obj) { System.out.println(obj); } public static void main(String[] args) throws IOException { //method1(); //method2(); //method3(); //method4(); method5(); } public static void method1() throws IOException { FileOutputStream fos = new FileOutputStream("E:\\1.txt"); fos.write("abc".getBytes());//write方法裡沒有字串參數,轉換為位元組數組 //位元組流不需要重新整理 fos.close(); } public static void method2() throws IOException { FileInputStream fis = new FileInputStream("E:\\1.txt"); /*int ch = 0; while((ch=fis.read())!=-1) //一次讀一個 sys((char)ch); fis.close();*/ byte[] buf = new byte[fis.available()];//fis.available是個數 int len = 0; while((len=fis.read(buf))!=-1) sys(new String(buf,0,len)); fis.close(); } /*拷貝圖片,位元組流*/ public static void method3() throws IOException { FileOutputStream fos = new FileOutputStream("E:\\2.jpg"); FileInputStream fis = new FileInputStream("E:\\1.jpg"); int ch = 0; while((ch=fis.read())!=-1) fos.write(ch); fos.close(); fis.close(); } /*拷貝mp3,通過緩衝區*/ public static void method4() throws IOException { BufferedOutputStream bufos=new BufferedOutputStream(new FileOutputStream("E:\\2.mp3")); BufferedInputStream bufis=new BufferedInputStream(new FileInputStream("E:\\1.mp3")); int ch = 0; while((ch=bufis.read())!=-1) bufos.write(ch); bufis.close(); bufos.close(); } public static void method5() throws IOException { //位元組流及其緩衝沒有readLine方法,先變為字元流緩衝區 InputStream in = System.in; //擷取鍵盤輸入對象 InputStreamReader isr = new InputStreamReader(in);//位元組流轉換為字元流 BufferedReader bufr = new BufferedReader(isr); //字元流緩衝區 String line = null; while((line=bufr.readLine())!=null) { if(line.equals("over")) break; sys(line); } bufr.close(); }}
java位元組流