1、讀文件 BufferedInputStream java
BufferedInputStream必須傳入一個InputStream(通常是FileInputStream)數組
經常使用方法:spa
//從該輸入流中讀取一個字節 public int read(); code
//今後字節輸入流中給定偏移量處開始將各字節讀取到指定的 byte 數組中。 blog
public int read(byte[] b,int off,int len)get
應用實例:it
import java.io.BufferedInputStream; import java.io.FileInputStream; /** * BufferedInputStream:緩衝輸入流 * FileInputStream:文件輸入流 */ public class FileReadToString { public static void main(String[] args){ try { FileInputStream fis=new FileInputStream("WynnNi.txt"); BufferedInputStream bis=new BufferedInputStream(fis); String content=null; //自定義緩衝區 byte[] buffer=new byte[10240]; int flag=0; while((flag=bis.read(buffer))!=-1){ content+=new String(buffer, 0, flag); } System.out.println(content); //關閉的時候只須要關閉最外層的流就好了 bis.close(); } catch (Exception e) { e.printStackTrace(); } } }
2、寫文件 BufferedOutputStreamio
建立一個新的緩衝輸出流,以將數據寫入指定的底層輸出流。class
經常使用方法:import
//向輸出流中輸出一個字節
public void write(int b);
//將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此緩衝的輸出流。
public void write(byte[] b,int off,int len);
//刷新此緩衝的輸出流。這迫使全部緩衝的輸出字節被寫出到底層輸出流中。
public void flush();
應用實例
/** * BufferedOutputStream:緩衝輸出流 * FileOutPutStream:文件輸出流 */ public class StringOutPutToFile { public static void main(String[] args){ try { FileOutputStream fos=new FileOutputStream("WynnNi.txt"); BufferedOutputStream bos=new BufferedOutputStream(fos); String content="xxxxxxxxx!"; bos.write(content.getBytes(),0,content.getBytes().length); bos.flush(); bos.close(); } catch (Exception e) { e.printStackTrace(); } } }
3、實際應用場景
被調用方如何將文件傳輸給調用方並在本地輸出文件
一、被調用方將文件讀入緩衝區byte[]
二、將緩衝區數據轉換成String傳遞,String str = Base64.getEncoder().encodeToString(bytes);
三、接收方將String反轉爲byte[],bytes=Base64.getDecoder().decode(str);
四、接收方將緩衝區輸出到文件