------------------字节流---------------------
生活随笔
收集整理的這篇文章主要介紹了
------------------字节流---------------------
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字節流:
輸入和輸出:1.參照物都是java程序來慘遭
2.Input輸入,持久化上的數據----》內存
3.Output輸出,內存---》硬盤
字節輸出流:
OutputStream:
定義:流按照方向可以分為輸入和輸出流,字節流可以操作任何數據,字符流只能操作純字符數據。
IO流父類:OutputStream和InputStream
IO流程序書寫步驟:
1.先導包
2.進行異常處理
3.釋放資源
方法:
1.void?close();
2.Write(byte[ ]? ?b);Write(byte[ ],int?off,int?len?);
代碼:
public class FileOutputStreamDemo {public static void main(String[] args) throws IOException {//步驟1創建流 子類對象 綁定數據目的FileOutputStream fos= new FileOutputStream("c:\\aaa.txt");//2 調用write() 方法 寫一個字節fos.write(97);//2.1 寫字節數組byte[] b={65,66,67,68};fos.write(b);// 2.2 寫字節數組的一部分fos.write(b, 1, 2);//2.3寫字符串 getBytes() 字符串轉字節fos.write("hello world".getBytes());// 3 close 關閉資源 fos.close();} }FileOutputStream(文件輸出流):
文件的續寫和換行符號:
/* \r\n換行 */ public static void main(String[] args) throws IOException {File file = new File("c:\\b.txt");FileOutputStream fos = new FileOutputStream(file,true);fos.write("hello\r\n".getBytes());fos.write("world".getBytes());fos.close(); }字節輸入流:
InputStream: abstract int? read();讀取下一個字節,返回-1讀取文件結束。
方法:read(byte[ ]?b);close();
代碼;
public class FileInputStreamDemo {public static void main(String[] args) {try {FileInputStream fis = new FileInputStream("c:\\aaa.txt");int len =0;while((len=fis.read())!=-1){System.out.print((char)len);}} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}} }字節數組讀取:
public static void main(String[] args) {try {FileInputStream fis = new FileInputStream("c:\\aaa.txt");//創建字節數組byte[] b = new byte[1024];int len=0;while((len=fis.read(b))!=-1){//字節數組轉字符串System.out.println(new String(b,0,len));}} catch (Exception e) {// TODO Auto-generated catch block e.printStackTrace();}}?
轉載于:https://www.cnblogs.com/duguangming/p/10602588.html
總結
以上是生活随笔為你收集整理的------------------字节流---------------------的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 探索RequestBody报com.al
- 下一篇: 栈(stack)和堆(heap)