Java 字节流


    字节流以字节的形式读写文件,不同于字符流,字节流可以读写非文本文件

  1. 读字节流
    //构造方法
    FileInputStream fis = new FileInputStream(file); //参数是File类型对象
    //读取
    fis.read(); //从文件读取一个字节的数据返回这个数据的int类型表示
    int temp;
    //利用循环读取文件所有
    while((temp = fis.read()) != -1){
    }
    //关闭字节流
    fis.close();
  2. 写字节流
    //构造方法
    FileOutputStream fos = new FileOutputStream(file2); //参数是File类型对象
    //写入
    fos.write(); //参数可以是int类型,也可以是byte数组
    //关闭字节流
    fos.close();
  3. BufferedInputStream
    //创建对象 构造参数是FileInputStream类型对象
    BufferedInputStream bis = new BufferedInputStream(fis);
    //读取文件字节
    bis.read(); //返回int类型数值 可以放入byte[]类型参数,读取的字节数据会存放到数组参数里
    //利用循环读取整个文件
    int temp;
    while ((temp = bis.read()) != -1) {}
  4. BufferedOutputStream
    //创建对象 参数是FileOutputStream类型对象
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    //将数据存入文件
    bos.write(); //参数可以是int类型,还可以是byte[]
  5. 复制文件
    public static void main(String[] args) throws Exception {
        File file = new File("源文件地址");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        File f = new File("新文件地址");
        if (!f.exists()) {
          f.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(f);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
    
        byte [] ls = new byte[1024];
        while ((bis.read(ls)) != -1) {
          bos.write(ls);
        }
    
        bos.flush();
        bos.close();
        fos.close();
        bis.close();
        fis.close();
    
    }
  6. InputStreamReader
    //创建对象 System.in表示从控制台读取数据
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //从控制台读取一行输入的数据
    String name = br.readLine();
  7. OutputStreamWriter
    //创建对象 System.out表示输出到控制台
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    //将数据输出到控制台
    bw.write("hello world");
  8. ByteArrayOutputStream和ByteArrayInputStream
    //创建对象 类似存储byte数组的集合
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //write()方法用来将数组存入流
    byte[] bt = new byte[1024];
    list.write(bt);
    //配合文件读取操作,可以将文件中的所有数据读到内存
    File file = new File("文件路径");
    FileInputStream fs = new FileInputStream(file);
    BufferedInputStream bp = new BufferedInputStream(fs);
    while((len= bp.read(bt))!=-1) {
    	baos.write(bt);
    }
    
    //创建对象
    ByteArrayInputStream bais = new ByteArrayInputStream(bt);
    //配合ByteArrayOutputStream将内存中的数据读出到应用程序用于操作
    bais = new ByteArrayInputStream(baos.toByteArray());
    byte [] bt2 = new byte[1024];
    while(bais.read(bt2) != -1){}