java位元組流
阿新 • • 發佈:2019-01-04
一 位元組流
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=newFileOutputStream("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(); //強轉字元型 加char 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((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(); }