Java IO流(二) 字节流

字节流常用来处理图片文件等,不包含编码表。

常用基本类之字节流:InputStream:OutputStream

1.FileInputStream和FileOutputStream

字节流和字符流的使用方法一样,需要注意的是因为操作的是最小数据单位,所以不需要刷新,但是需要关闭流。

写入:

FileOutputStream fos = new FileOutputStream("/Volumes/Function/G/demo.txt");//创建文本文件    
fos.write("abc".getBytes());//写入流中     
fos.close();//关闭之前会刷新一次内部缓冲,将数据刷到目的地中,flush刷新会继续使用。    
读取:

1.1

FileInputStream fis  = new FileInputStream("/Volumes/Function/G/demo_test.txt") ;  
byte[] buf = new byte[1024];  
int len = 0;  
while((len = fis.read(buf)) != -1){  
    System.out.println(new String(buf,0,len));  
}  
fis.close();
1.2

FileInputStream fis  = new FileInputStream("/Volumes/Function/G/demo_stream.txt") ;  
int num = fis.available();//获取到当前文本中所有的字节数,便于定义一个数据量大小合适的数组  
byte[] buf = new byte[num];  
fis.read(buf);  
System.out.println(new String(buf));  
fis.close();  
复制一张图片:

FileOutputStream fos = new FileOutputStream("/Volumes/Function/G/112_copy.jpg");  
FileInputStream fis  =new FileInputStream("/Volumes/Function/G/112.jpg");  
byte[] buf = new byte[1024*1024];  
int len  = 0;  
while((len = fis.read(buf)) != -1){  
    fos.write(buf,0,len);  
}  
if (fis != null) {  
    fis.close();  
}  
if (fos != null) {  
    fos.close();  
} 
2.BufferedOutputStream和BufferedInputStream

字节流缓冲区和字符流缓冲区用法相似,这里不再赘述。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值