FileInputStream和FileOutputStream的基本用法

FileOutputStream(字节流)

  1. void write( byte b[] )

    • 直接写入指定字符的字节流

      @Test
      public void writeTest() throws Exception {
          File file = new File("E:/test.txt");
          FileOutputStream fos = new FileOutputStream(file,true);
          byte[] b = {65,66,67,68,69,70};
          byte[] b1 = "赵玉龙".getBytes();
          fos.write(b);
          fos.write("\n".getBytes());
          fos.write(b1);
          fos.write("\n".getBytes());
          fos.close();
      }
      
  2. void write( byte b[], int off, int len )

    • 通过缓存多次写入

      @Test
      public void copyImgTest() throws IOException{
          long startTime = System.currentTimeMillis();
          FileInputStream fis = new FileInputStream("D:/img/th.jpg");
          FileOutputStream fos = new FileOutputStream("D:/img/th_copy.jpg");
          byte[] buf = new byte[1024];
          int len;
          //读并写
          while ((len = fis.read(buf)) != -1){
              fos.write(buf,0,len);
          }
          long endTime = System.currentTimeMillis();
          if (buf != null){
              System.out.println("复制成功!\n用时:" + (endTime-startTime) + "ms");
          }
      }
      

FileInputStream(字节流)

  1. int read()

    • 一次只读一个字符,返回该字符的ASCII码

       @Test
       public void readIntTest() throws Exception{
           FileInputStream fis = new FileInputStream("E:/test.txt");
           int read;
           //一个字符一个字符的读,返回值为对应字符的ASCII码
           while ((read = fis.read()) != -1){
               System.out.println(read);
           }
           fis.close();
       }
      
  2. int read(byte[] b)

    • 一次向b数组读取读取该数组容量大小的字节

      @Test
      public void readStringTest() throws Exception{
          FileInputStream fis = new FileInputStream("E:/test.txt");
          byte[] buf = new byte[1024];
          int len;
          while ((len = fis.read(buf)) != -1){
              System.out.println(new String(buf,0, len));
          }
          String result = new String(buf);
          System.out.println(result);
          fis.close();
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值