字节流

1.1 字节输出流OutputStream

OutputStream此抽象类是表示输出字节流的所有类的超类。操作的数据都是字节,定义了输出字节流的基本共性功能方法。

 

1.1.1 FileOutputStream

l 构造方法

 传File对象  创建一个向指定File 对象表示的文件中写入数据的文件输出流

传入字符串  创建一个向具有指定名称的文件中写入数据的输出文件流

1.1.2 给文件中续写和换行

FileOutputStream的构造函数中,可以接受一个boolean类型的值,如果值true,就会在文件末位继续添加。

 

public class FileOutputStreamDemo2 {
    public static void main(String[] args) throws Exception {
        File file = new File("c:\\file.txt");
        FileOutputStream fos = new FileOutputStream(file, true);
        String str = "\r\n"+"aaa";
        fos.write(str.getBytes());
        fos.close();
    }
}

 

1.2 IO异常的处理

public class FileOutputStreamDemo3 {
    public static void main(String[] args) {
        File file = new File("c:\\file.txt");
        //定义FileOutputStream的引用
        FileOutputStream fos = null;
        try {
            //创建FileOutputStream对象
            fos = new FileOutputStream(file);
            //写出数据
            fos.write("abcde".getBytes());
        } catch (IOException e) {
            System.out.println(e.toString() + "----");
throw new RuntimeException("文件写入失败,重试");

        } finally {
            //一定要判断fos是否为null,只有不为null时,才可以关闭资源
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭资源失败");
                }
            }
        }
    }
}

1.3 字节输入流InputStream

l int read():读取一个字节并返回,没有字节返回-1.

l int read(byte[]): 读取一定量的字节数,并存储到字节数组中,返回读取到的字节数。

1.3.1 FileInputStream

 

l 构造方法

传file对象 通过打开一个到市级文件的连接来创建一个FileInputStream 改文件通过文件系统中的File对象file指定

传字符串 通过打开一个到市级文件加的连接来创建一个FileInputStream  改文件通过文件系统中的路径名 指定

1.3.2 FileInputStream类读取数据read方法

read()  从输入流中读取数据的下一个字节

 

1.3.3 读取数据read(byte[])方法

read(byte[] b)从输入流中读取一定数量的字节 并将其存储在缓冲区数组b中

 

posted @ 2020-07-31 16:36  asgetharytmjxtyk,dxh  阅读(103)  评论(0编辑  收藏  举报