Java基础 FileInputStream/ FileOutputStream / 字节输入流 字节输出流实现文件的复制

FileInputStream/FileOutputStream的笔记:

/**(FileInputStream/FileOutputStream四个步骤: ①声明②加载地址③read/write④close流)
 * FileInputStream fis
 *      1.public int read( byte[] b, int off, int len) throws IOException
 *                 //从fis流读取字符, 后两项规定存储位置(左闭右开);默认最多b.length字节的数据到字节数组
 *                 //int 返回值表示每次读取的字符的Byte 个数.
 *  FileOutputStream fos
 *      1.输出的物理文件可以不存在,若不存在则可以自动创建!若存在,则会进行覆盖!
 *      2.public FileOutputStream(String name,boolean append)  throws FileNotFoundException
 *                        //如果第二个参数是true ,则字节将写入文件的末尾而不是开头。
 */

三个实验的代码:

public class Test_FileInputStream {
  @Test    //实验1目的: 建立byte读入流,从文件读取数据, 并建立异常保护机制
  public void testFileInputStream1(){

    File f1=new File("D:\SZS文件夹\IO\hello.txt");
    FileInputStream fis=null;
    byte[] date=new byte[4];
    int num;
    try {
      fis=new FileInputStream(f1);
      while((num = fis.read(date,0,4) ) != -1){
            String s= new String(date);
        System.out.println("每4个byte打印读入流:"+s);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        fis.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

  @Test   //实验2目的: 建立byte输出流,并建立异常保护机制
  public void testFileOutputStream1(){
    File f1=new File("D:\SZS文件夹\IO\hello.txt");
    FileOutputStream fos=null;
   String s="this a testFileOutputStream1!";  //没毛病,s.getBytes("UTF-8")
    try {
      fos= new FileOutputStream(f1,true);
      fos.write(s.getBytes("UTF-8"));        //包装类可以轻松转换类型
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        fos.close();
      }catch (IOException e){
        e.printStackTrace();
      }
    }
  }

  @Test  //实验3目的: 从硬盘读取一个文件,并写到另一个文件 (相当于文件的复制!)
  public void  TestCopyFile() throws IOException {
      // ①声明②加载地址③read/write④close流)
      File f1=new File("D:\SZS文件夹\IO\hello.txt");
      File f2=new File("D:\SZS文件夹\IO\hello_copy.txt");
      FileInputStream fis=null;
      FileOutputStream fos=null;

    try {
      fis= new FileInputStream(f1);
      fos= new FileOutputStream(f2);
          //3.实现文件的复制
      byte[] b=new byte[20];
      int len=5;
      while( (len = fis.read(b)) !=-1){

          fos.write(b,0,len);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }finally {
      fis.close();
      fos.close();
    }
  }
}

控制台的输出结果:

每4个byte打印读入流:this
每4个byte打印读入流: a t
每4个byte打印读入流:estF
每4个byte打印读入流:ileO
每4个byte打印读入流:utpu
每4个byte打印读入流:tStr
每4个byte打印读入流:eam1
每4个byte打印读入流:!thi
每4个byte打印读入流:s a 
每4个byte打印读入流:test
每4个byte打印读入流:File
每4个byte打印读入流:Outp
每4个byte打印读入流:utSt
每4个byte打印读入流:ream
每4个byte打印读入流:1!am

本地文件结果:

原文地址:https://www.cnblogs.com/zhazhaacmer/p/9800111.html