Java字节流详解

字节流

字节流不仅可以操作字节流还可以操作字符,以及其他的媒体文件

InputStream字节输入流

InputStream类是字节输入流的基类
在这里插入图片描述

InputStream类

序号方法描述
1int available() 从下一次调用此输入流的方法返回可从该输入流读取(或跳过)的字节数,而不会阻塞。
2void close() 关闭此输入流并释放与流相关联的任何系统资源。
3void mark(int readlimit) 标记此输入流中的当前位置。
4boolean markSupported() 测试此输入流是否支持 mark和 reset方法。
5abstract int read() 从输入流读取数据的下一个字节。
6intread(byte[] b) 从输入流中读取一些字节数,并将它们存储到缓冲器阵列 b 。
7intread(byte[] b, int off, int len) 从输入流读取最多 len个字节的数据到字节数组。
8byte[] readAllBytes() 从输入流读取所有剩余字节。
9intreadNBytes( byte [] b, int off, intlen)i 将所请求的字节数从输入流读入给定的字节数组。
10voidreset() 将此流重新定位到最后在此输入流上调用 mark方法时的位置。
11longskip(``longn) 跳过并丢弃来自此输入流的 n字节的数据。
12longtransferTo(OutputStream out) 从该输入流中读取所有字节,并按读取的顺序将字节写入给定的输出流。

ByteInputStream类

  • 字节数组输入流在内存中创建一个字节数组缓冲区,从输入流读取的数据保存在该字节数组缓冲区中

    创建方式:

    1、接收字节数组作为参数

    ByteArrayInputStream bas = new ByteArrayInputStream(byte [] a)

    2 、接收一个字节数组和两个整型变量 off、len,off表示第一个读取的字节,len表示读取字节的长度

    ByteArrayInputStream bas = new ByteArrayInputStream(byte [] a,int off,int len)

    常用方法
    序号方法描述
    1public int read() 从此输入流中读取下一个数据字节
    2public int read(byte[] r,int off,int len) 将最多len个数据字节从此输入流读入字节数组
    3public int available() 返回可不发生阻塞地从此输入流读取的字节数
    4public void mark (int read)设置流中的当前标记位置
    5public long skip(long n) 从此输入流中跳过n个输入字节
    实列
      import java.io.ByteArrayInputStream;
      import java.io.ByteArrayOutputStream;
      import java.io.IOException;
      
      /**
       * @program: IOtest
       * @description: 测试ByteArrayInputStream
       * @author: 雨沐淋风
       * @create: 2020-10-23
       **/
      public class TestByteArrayInputStream {
          public static void main(String[] args) throws IOException {
              ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
              while (bOutput.size() != 10){
                  bOutput.write(System.in.read());
              }
      
              byte[] bytes = bOutput.toByteArray();
              System.out.println("Print the content");
      
              for (int i = 0; i < bytes.length; i++) {
                  System.out.println((char)bytes[i] + "  ");
              }
              System.out.println("     ");
      
              int c;
              ByteArrayInputStream bInput = new ByteArrayInputStream(bytes);
      
              System.out.println("Converting characters to Upper case " );
              for(int y = 0 ; y < 1; y++ ) {
                  while(( c= bInput.read())!= -1) {
                      System.out.println(Character.toUpperCase((char)c));
                  }
                  bInput.reset();
              }
          }
      }
    
  • 运行结果

        abcdwefijijiji
        Print the content
        a  
        b  
        c  
        d  
        w  
        e  
        f  
        i  
        j  
        i  
             
        Converting characters to Upper case 
        A
        B
        C
        D
        W
        E
        F
        I
        J
        I
    

FileInputStream 类

  • FileInputStream的构造方法需要指定文件的来源,通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的 File 对象 file 指定。

    创建方式:

    1、通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。

    FileInputStream fis = new FileInputStream(File file)

    2、通过使用文件描述符 fdObj创建 FileInputStream ,该文件描述符表示与文件系统中的实际文件的现有连接。

    FileInputStream fis = new FileInputStream(FileDescriptor fdObj)

    3、通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。

    FileInputStream fis = new FileInputStream(String name)

    常用方法
    返回类型方法名描述
    intavailable()返回从此输入流中科院读取的剩余字节数的估值,而不会被下一次调用此输入流的方法阻塞
    voidclose()关闭此文件输入流并释放与流相关的任何系统资源
    protected voidfinalize()确保当这个文件输入流的close方法没有更多的应用时被调用
    FileChannelgetChannle()返回与此文件输入流相关联的唯一FileChannel对象
    FileDescriptorgetFD()返回表示与此FileInputStrem正在使用的文件系统中文件的连接的FileDescriptor对象
    intread()从该输入流读取一个字节的数据
    intread(byte[] b)从该输入流读取最多b.length个字节的数据为字节数组
    intread(byte[] b,int off,int len)从该输入流读取最多len字节的数据为字节数组
    longskip(long n)跳过从输入流中丢弃n字节的数据
    运用实例
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * @program: IOtest
     * @description: 测试FIleInputStream
     * @author: 雨沐淋风
     * @create: 2020-10-23
     **/
    public class TestFieInputStream {
        public static void main(String[] args) {
    
            FileInputStream fileInput = null;
            try {
                // test.txt 内容:InputStream test
                fileInput = new FileInputStream("test.txt");
                byte[] bytes = new byte[1024]; //一次读取多个字节
                int len = 0;
                try {
    //                if ((len = fileInput.read(bytes,2,5)) != -1) {
    //                    System.out.println(new String(bytes));
    //                }
    //               结果:  Input                                                                 
                    if ((len = fileInput.read(bytes)) != -1) {
                        System.out.println(new String(bytes));
                    }
    //               结果: InputStream test                       
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
    
                try {
                    if (fileInput != null) {
                        fileInput.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * @program: IOtest
     * @description: 测试FIleInputStream
     * @author: 雨沐淋风
     * @create: 2020-10-23
     **/
    public class TestFieInputStream {
        public static void main(String[] args) {FileInputStream fileInputStream = null;
            try {
                // test.txt 内容:InputStream test
                fileInputStream = new FileInputStream("test.txt");
                try {
                    //跳过前面9个字符
                    long len = fileInputStream.skip(9);
                    //获取流中可以读取的剩余字节数
                    int available = fileInputStream.available();
                    System.out.println(available);
                    int ch = 0;
                    // 调用read()方法,一次读一个字节,自动往下读
                    while ((ch = fileInputStream.read()) != -1){
                        System.out.println((char)ch);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                try {
                    if (fileInputStream != null){
                        fileInputStream.close();
                    }    
                }catch (IOException e){
                    throw new RuntimeException("关闭文件异常");
                }   
            }
        }
    }
    
    7
    a
    m
     
    t
    e
    s
    t
    

OutputStream 字节输出流

OutputStream是一个抽象类,表示字节输出流的超类。输出流接收到输出字节并将其发送到某个接收器上

在这里插入图片描述

常用方法
返回类型方法名描述
voidclose()关闭此输出流并释放与此流相关联的任何资源
voidflush()刷新此输出流并强制任何缓冲的输出字节被写出
voidwrite(byte[] b)将b.length字节从字节数组写入此输出流
voidwrite(byte[] b,int off,int len)从指定的字节数组写入len个字节,从偏移量为off的位置开始输出到输出流
abstractwrite(int b)将指定的字节写入此输出流

FileInputStream类

文件输出流是用于将数据写入到输出流File或一个FileDescriptor。文件是否可用或者可能被创建取决与底层平台。特别是有些平台之被允许一次只能打开一个文件来写入FileOutputStream。在这种情况下,如果所涉及的文件已经打开,则此类中的构造函数将失败

FileOutputStream用于写入诸如图像数据的原始字节流。对于写入字符流,考虑使用Filewriter。

构造方法
方法名描述
FileOutputStream(File file)创建文件输出流以写入由指定的File对象表示的文件
FileOutputStream(File file,boolean append)创建文件输出流以写入有指定的File对象表示文件,后面append参数true表示后面追加,false表示不追加覆盖原文件
FileOutputStream(FileDescriptor fobj)创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接
FileOutputStream(String name)创建文件输出流以指定的名称写入文件
FileOutputStream(String name,boolean append)创建文件输出流以指定的名称写入文件,append参数:true表示原文件后面追加,false表示覆盖原文件
常用方法
返回类型方法名描述
voidclose()关闭文件输出流并释放与此流相关联的任何系统资源
protected voidfianlize()清理与文件的连接,并确保当没有更多的引用此流时,将调用此文件输出流的close方法
FileChannelgetFileChannel()返回与此文件输出流相关联的唯一的FileChannel对象
FileDescriptorgetFD()返回与此输出流相关联的文件描述符。
voidwrite(byte[] b)将b.length个字节从指定的字节数组写入此文件输出流。
voidwrite(byte[] b,int off,int len)将len个字节从位置偏移量为off的位置指定字节数组写入此输出流
voidwrite(int b)将指定的字节写入此文件输出流中
代码示例
import java.io.*;

/**
 * @program: IOtest
 * @description:测试FileOuputStream
 * @author: 雨沐淋风
 * @create: 2020-10-23
 **/
public class TestFileOutputStream {
    public static void main(String[] args) {
        //创建一个新文件
        File file = new File("TestFileOutputStream.txt");
        try {
            //创建file对应的FileOutputStream对象
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            PrintWriter printWriter = new PrintWriter(fileOutputStream);
            printWriter.print("TestOutputStream");
            printWriter.close();
			//创建file对应的FileOutputStream对象,第二参数是true表示在原文件的后面追加内容
            FileOutputStream fileOutputStream1 = new FileOutputStream(file, true);
            PrintStream printStream = new PrintStream(fileOutputStream1);
            printStream.print("  append");
            printStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.*;

/**
 * @program: IOtest
 * @description:将test.txt文件的内容拷贝到copy.txt中
 * @author: 雨沐淋风
 * @create: 2020-10-23
 **/
public class TestFileOutputStream {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("test.txt");
            fileOutputStream = new FileOutputStream("copy.txt");
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1){
                fileOutputStream.write(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (fileOutputStream != null){
                    fileOutputStream.close();
                }
                if(fileInputStream !=null){
                    fileInputStream.close();
                }
            }catch (IOException e){
                throw new RuntimeException("关闭文件异常");
            }
        }
    }
}

        try {
            if (fileOutputStream != null){
                fileOutputStream.close();
            }
            if(fileInputStream !=null){
                fileInputStream.close();
            }
        }catch (IOException e){
            throw new RuntimeException("关闭文件异常");
        }
    }
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值