JAVA IO 学习

  1. package ioTest.io2;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6.   
  7. /* 
  8.  * IO: 
  9.  * 字符流:Writer,Reader 
  10.  * 字节流:OutPutStream,InPutStream 
  11.  *  
  12.  * 下面的实例仍然是对文本文件进行操作。但是字节流大多用于操作非文本文件, 
  13.  * 比如音频视频图片等文件 
  14.  */  
  15.   
  16. public class FileSteam {  
  17.   
  18.     public static void main(String[] args) throws IOException {  
  19.         //writeFile();  
  20.         readFile_3();  
  21.     }  
  22.     //三种不同的方式的读取文件  
  23.     //读一个字节  
  24.     public static void readFile_1() throws IOException {  
  25.         FileInputStream fInputStream=new FileInputStream("ioTest1.txt");  
  26.         int ch;  
  27.         while((ch=fInputStream.read())!=-1)  
  28.         {  
  29.             System.out.println((char)ch);  
  30.         }  
  31.         fInputStream.close();  
  32.     }  
  33.     //读指定长度字节数组  
  34.     public static void readFile_2() throws IOException {  
  35.         byte[] buf=new byte[1024];  
  36.         int len=0;  
  37.         FileInputStream fInputStream=new FileInputStream("ioTest1.txt");  
  38.         while((len=fInputStream.read(buf))!=-1)  
  39.         {  
  40.             System.out.println(new String(buf, 0, len));  
  41.         }  
  42.         fInputStream.close();  
  43.     }  
  44.     //读全长度的字节数组,也就是说一次性读取  
  45.     public static void readFile_3() throws IOException {  
  46.         FileInputStream fInputStream=new FileInputStream("ioTest1.txt");  
  47.         int len=fInputStream.available();  
  48.         byte[] buf=new byte[len];  
  49.         fInputStream.read(buf);  
  50.         System.out.println(new String(buf));  
  51.         fInputStream.close();  
  52.     }  
  53.     /* 
  54.      * 比较以上三种方式,第二种方式比第一方式更优越。 
  55.      * 第三种方式在读写一些小文件的时候,看似是比前两种方式好。 
  56.      * 但是文件很大的情况下,在第三种情况下,如果内存一次性不能存储这么大容量的文件时候 
  57.      * 就会出现内存溢出。 
  58.      * 所以最终和最常用的我们有限选择第二种方式。 
  59.      */  
  60.     public static void writeFile() throws IOException {  
  61.         //创建一个流  
  62.         FileOutputStream foStream=new FileOutputStream("ioTest1.txt");  
  63.         foStream.write("abcde".getBytes());  
  64.         //foStream.flush();  
  65.         //发现没有上面的话,仍然写入成功。原因是字节操作时读写操作的最小单位。  
  66.         //所以这里暂时不用flush。字符操作实际上底层是基于字节的,所以又两个字节-一个字符的一个缓冲处理  
  67.         //所以需要刷新  
  68.         foStream.close();  
  69.     }  

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值