java文件写入_JAVA文件读写操作

一、读文件 BufferedInputStream

BufferedInputStream必须传入一个InputStream(一般是FileInputStream)

常用方法:

//从该输入流中读取一个字节 public int read();

//从此字节输入流中给定偏移量处开始将各字节读取到指定的 byte 数组中。

public int read(byte[] b,int off,int len)

应用实例:

importjava.io.BufferedInputStream;importjava.io.FileInputStream;/*** BufferedInputStream:缓冲输入流

* FileInputStream:文件输入流*/

public classFileReadToString {public static voidmain(String[] args){try{

FileInputStream fis=new FileInputStream("WynnNi.txt");

BufferedInputStream bis=newBufferedInputStream(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 classStringOutPutToFile {public static voidmain(String[] args){try{

FileOutputStream fos=new FileOutputStream("WynnNi.txt");

BufferedOutputStream bos=newBufferedOutputStream(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、接收方将缓冲区输出到文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值