java字节流
一? 字節流
1.1字節輸出流OutputStream
OutputStream是一個抽象類,操作的數據都是字節。
輸出流中定義都是寫write方法,如下圖:
1.1.1 FileOutputStream類
OutputStream有很多子類,其中子類FileOutputStream可用來寫入數據到文件。FileOutputStream類,即文件輸出流,是用于將數據寫入 File的輸出流。
構造方法:
將數據寫入文件中
public static void method01() throws IOException{//創建字節輸出流對象//如果該文件有則覆蓋,如果沒有則覆蓋FileOutputStream fos=new FileOutputStream("E:\\java\\demo.txt");fos.write(100);//ASCII碼//釋放資源 fos.close();}
public static void method02() throws IOException{//創建字節輸出流對象//如果該文件有則覆蓋,如果沒有則覆蓋FileOutputStream fos=new FileOutputStream("E:\\java\\demo.txt");//byte[] bytes={97,98,99,100};//fos.write(bytes,1,1);//字符串轉字節數組fos.write("你好嗎,中國".getBytes());//釋放資源 fos.close();}
public static void method03() throws IOException{//創建字節輸出流對象//如果該文件有則覆蓋,如果沒有則覆蓋FileOutputStream fos=new FileOutputStream("E:\\java\\demo.txt",true);//換行 \r\n//字符串轉字節數組fos.write("hello,java".getBytes());//釋放資源 fos.close();}
給文件續寫和換行時,在FileOutputStream的構造函數中,可以接受一個boolean類型的值,如果值true,就會在文件末位繼續添加。
1.2字節輸入流InputStream
InputStream是一個抽象類,定義了讀的方法
1.2.1 FileInputStream類
FileInputStream類是InputStream的實現類,用它來讀取文件內容
構造方法有
用它來讀取數據
1 單個字節讀
public static void method01() throws IOException{//明確數據源FileInputStream fis=new FileInputStream("E:\\java\\demo.txt");//從文件中讀取一個字節int len1=fis.read();//強轉字符型 加charSystem.out.println((char)len1);len1=fis.read();System.out.println((char)len1);len1=fis.read();System.out.println((char)len1);len1=fis.read();System.out.println((char)len1);len1=fis.read();System.out.println((char)len1);len1=fis.read();System.out.println(len1);//釋放資源 fis.close();}
2.單個字節循環讀
public static void method02() throws IOException{FileInputStream fis=new FileInputStream("E:\\java\\demo.txt");int len=0;while((len=fis.read())!=-1){System.out.println((char)len);}//釋放資源 fis.close();}
3.用數組的形式一個個讀
public static void method03() throws IOException{FileInputStream fis=new FileInputStream("E:\\java\\demo.txt");//創建數組byte[] bytes=new byte[2];int len=fis.read(bytes);System.out.println(new String(bytes));System.out.println(len);len=fis.read(bytes);System.out.println(new String(bytes));System.out.println(len);len=fis.read(bytes);System.out.println(new String(bytes));System.out.println(len);//釋放資源 fis.close();}
4.用數組的形式循環讀
public static void method04() throws IOException{FileInputStream fis=new FileInputStream("E:\\java\\demo.txt");//創建數組byte[] bytes=new byte[2];int len=0;while((len=fis.read(bytes))!=-1){System.out.println(new String(bytes,0,len));}//釋放資源 fis.close();}
字節流的練習:進行文件的復制
//文件的復制public static void method05() throws IOException{//數據源FileInputStream fis=new FileInputStream("E:\\java\\demo.txt");//目的地FileOutputStream fos=new FileOutputStream("F:\\demo.txt");//開始復制int len=0;while((len=fis.read())!=-1){fos.write(len);}//釋放資源 fis.close();fos.close();}
?
轉載于:https://www.cnblogs.com/zzq123/p/10219142.html
總結
- 上一篇: 现在佳能单反相机5d3机身多少钱
- 下一篇: 三星堆博物馆包括遗址吗