一, 读文件 BufferedInputStream
BufferedInputStream 必须传入一个 InputStream(一般是 FileInputStream)
常用方法:
- // 从该输入流中读取一个字节 public int read();
- // 从此字节输入流中给定偏移量处开始将各字节读取到指定的 byte 数组中.
- public int read(byte[] b,int off,int len)
应用实例:
- 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();
- }
- }
- }
二, 写文件 BufferedOutputStream
创建一个新的缓冲输出流, 以将数据写入指定的底层输出流.
常用方法:
- // 向输出流中输出一个字节
- 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();
- }
- }
- }
三, 实际应用场景
被调用方如何将文件传输给调用方并在本地输出文件
1, 被调用方将文件读入缓冲区 byte[]
2, 将缓冲区数据转换成 String 传递, String str = Base64.getEncoder().encodeToString(bytes);
3, 接收方将 String 反转为 byte[],bytes=Base64.getDecoder().decode(str);
4, 接收方将缓冲区输出到文件
来源: http://www.bubuko.com/infodetail-3364422.html