Java学习2023.7.21(I/O流)

 

目录

一、输入输出

1、File类

1> boolean exists() 

2>  boolean isDirectory()

3>  boolean isFile()

4>String getName()

5>boolean delete()

6>boolean createNewFile()

7>boolean mkdir()

8>其余用法

 2、FileInputStrem类

 1> 利用循环读取文件所有数据

2> while遍历输出数据

3> int read(byte[] b) throws IOException

3、FileOutputStream类

 1>  创建FileOutputStream类对象

 2>创建FileOutputStream实例

 4、实例:实现对一个文本文件的复制

二、输入、输出处理

1、InputStreamReader

1> 循环读取数据

2> 关闭流( .close() )

3> 编码格式判断

2、FileReader

3、BufferedReader

1> 创建对象

2> 循环输出

4、OutputStreamWriter

5、FileWriter

6、BufferedWriter

1>.witer() 写入

2>.newLine() 换行

7、实例:替换pet. template文件中的某些内容

8、DataInputStream  和  DataOutputStream

1>DataInputStream

2>DataOutputStream

3>循环读取数据

9、ObjectInputStream     和    ObjectOutputStream

1> ObjectOutputStream

2> ObjectInputStream


一、输入输出

1、File类

创建一个File类对象,指向电脑F盘中Demo文件夹里的test文件夹(这里的位置可以自己选择)

File file1 = new File("F:\\Demo\\test");
1> boolean exists() 

测试此抽象路径名表示的文件或目录是否存在。如果存在,返回true,否则返回false

        boolean result1 =file1.exists();
        System.out.println("file1对象指向的文件夹存在:"+result1);//true
2>  boolean isDirectory()

测试此抽象路径名表示的文件是否是一个目录。


3>  boolean isFile()

测试此抽象路径名表示的文件是否是一个标准文件。

        boolean result3 =file1.isFile();
        System.out.println("file1对象指向的路径是一个文件:"+result3);//false
        boolean result4 =file1.isDirectory();
        System.out.println("file1对象指向的路径是一个文件夹:"+result4);//true
4>String getName()

返回由此抽象路径名表示的文件或目录的名称。

        System.out.println("file1对象指向的文件夹名称:"+file1.getName());
        System.out.println("file2对象指向的文件名称:"+file2.getName());
5>boolean delete()

 删除此抽象路径名表示的文件或目录。 删除成功返回true,删除失败返回false

        System.out.println("file1对象指向的文件夹删除成功:"+file1.delete());
        System.out.println("file2对象执行的文件删除成功:"+file2.delete());
6>boolean createNewFile()

当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。
如果file1对象指向的文件不存在,就创建文件

        if(!file1.exists()){
            try {
                boolean result1=file1.createNewFile();
                System.out.println("文件创建成功");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            System.out.println("文件已存在,不能再创建");
        }
7>boolean mkdir()

创建此抽象路径名指定的目录

        if(!file2.exists()){
            file2.mkdir();
            System.out.println("目录创建成功");
        }else{
            System.out.println("目录已存在,不能再创建");
        }

         //如果创建的目录的父目录不存在,使用mkdir()方法创建目录,是不能创建成功的
        //boolean result2 =file3.mkdir();
        //boolean mkdirs() :创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。

        File file3 = new File("F:\\Demo\\b\\c\\d\\e");
        boolean result2 =file3.mkdirs();
        System.out.println("file3指向的目录创建成功:"+result2);
8>其余用法

 

 

 2、FileInputStrem类

 创建对象(两句可以写成一句)

        File file = new File("F:/Demo/aa.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

int available() :返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。

 int read():从此输入流中读取一个数据字节。

 读取一个数据字符:一个方法内读取后,下次读取会在上次读取的数据后接着读取

 1> 利用循环读取文件所有数据
        int count =fileInputStream.available();
        System.out.println("count:"+count);

        for(int i =1;i<=count;i++){
            int num = fileInputStream.read();
            System.out.print((char)num);
        }

因为count是一个估计值,不能确保正确性,所以上面的方式不合适

2> while遍历输出数据
        int number;
//        StringBuffer stringBuffer=new StringBuffer("");
        while((number=fileInputStream.read())!=-1){
            System.out.print((char)number);
//            stringBuffer.append((char)number);
        }

//        System.out.println("\nstringBUffer:"+stringBuffer);
3> int read(byte[] b) throws IOException

        从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
        在某些输入可用之前,此方法将阻塞。

        读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。

            byte[] bytes = new byte[1024];
            int num =fileInputStream.read(bytes);
            //将读取的数据输出:遍历bytes数组
            for(int i =0;i<num;i++){
                System.out.print((char)bytes[i]);
            }

不管前面代码的执行情况,最终流都应该进行关闭,如果流开启了(不为不为null)就进行关闭

 int read(byte[] b, int off, int len) 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。

            byte[] bytes =new byte[1024];
            //int read(byte[] b, int off, int len) 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
			//如果 len 不为 0,则在输入可用之前,该方法将阻塞;否则,不读取任何字节并返回 0。
            /*
            * 参数:
                b - 存储读取数据的缓冲区。
                off - 目标数组 b 中的起始偏移量。
                len - 读取的最大字节数。

               返回值:读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
            * */
            int num =fileInputStream.read(bytes,3,5);
            System.out.println("读取的字节总数:"+num);

            for (int i =0;i<bytes.length;i++){
                System.out.print((char)bytes[i]);
            }

3、FileOutputStream类

 1>  创建FileOutputStream类对象


        //使用FileOutputStream(File file)和FileOutputStream(String filePath)构造方法向文件中写入数据时,会覆盖文件中原来已经存在的数据

        File file = new File("F:/Demo/aa.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        //开始将数据写入到文件中,调用相应方法即可实现
        fileOutputStream.write(65);

        System.out.println("数据写入完毕");

        FileOutputStream(File file,boolean bool)        和        FileOutputStream(String filePath,boolean bool)        构造方法

当布尔值为false的时候会覆盖文件中原来已经存在的数据

当布尔值为true的时候,写入的数据会写到文件内容的末尾,不会覆盖文件中已经存在的数据

 2>创建FileOutputStream实例

 如果相应的文件并不存在,则会自动创建一个空的文件

            fileOutputStream = new FileOutputStream("F:/Demo/bb.txt",true);

            //创建要写入的数据
            String str = "Java IO very good";
            byte[] bytes =str.getBytes();
            fileOutputStream.write(bytes);
            System.out.println("数据写入完毕")

 4、实例:实现对一个文本文件的复制

        FileInputStream fileInputStream =null;
        FileOutputStream fileOutputStream =null;
        try {
            fileInputStream = new FileInputStream("F:/Demo/aa.txt");
            fileOutputStream = new FileOutputStream("F:/Demo/cc.txt");

            //使用循环的方式读取数据,然后将读取的数据写入到另一个文件中
            int num;
            while((num=fileInputStream.read())!=-1){
                //在这里不是将读取的numz值进行输出,而是将读取的num值写入另一个文件
                fileOutputStream.write(num);
            }
            System.out.println("文件复制完毕");

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭多个流是有顺序的,先开的流后关,后开的流先关
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

二、输入、输出处理

1、InputStreamReader

创建对象

        File file = new File("F:/Demo/aa.txt");
        InputStream inputStream = null;
        InputStreamReader inputStreamReader =null;
        try {
            //InputStream类是抽象类,不能通过new的形式直接实例化,可以通过多态的形式,将InputStream类的引用指向其子类FileInputStream类的实例
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        inputStreamReader = new InputStreamReader(inputStream);
1> 循环读取数据
        int num;
        while(true){
            try {
                if (((num=inputStreamReader.read())!=-1)) {
//这里的判断条件用于:判断读取的数据是否 不是 空值,空值就返回-1
                    System.out.print((char)num);
                }else{
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
2> 关闭流( .close() )
        if(inputStreamReader!=null){
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        if(inputStream!=null){
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
3> 编码格式判断
        System.out.println("IDEA平台编码格式:"+System.getProperty("file.encoding"));

        inputStreamReader = new InputStreamReader(inputStream,"GBK");

这里是创建对象结尾,在里面加入编码的格式就可以了

2、FileReader

读取数据举例:

        //创建FileReader类对象
        FileReader fileReader = new FileReader("F:/Demo/aa.txt");

        //读取数据
        int num ;
        while((num=fileReader.read())!=-1){
            System.out.print((char)num);
        }

        fileReader.close();

3、BufferedReader

1> 创建对象
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("F:/Demo/dd.txt")));

该对象创建类似于“嵌套”,一个套一个

注:

BufferedReader有个读取行的功能    .readLine()     可进行一行的读取!

        String str1 =bufferedReader.readLine();
        System.out.println(str1);

        String str2 =bufferedReader.readLine();
        System.out.println(str2);

2> 循环输出
        //使用循环的方式读取文件中所有的行
        String str;
        while((str=bufferedReader.readLine())!=null){
            System.out.println(str);
        }

        bufferedReader.close();

4、OutputStreamWriter

创建对象

OutputStream outputStream = new FileOutputStream(file);//写入的数据会覆盖文件中原有的数据

        File file = new File("F:\\Demo\\cc.txt");
        OutputStream outputStream = new FileOutputStream(file,true);//添加一个布尔值true,写入的数据会添加在文件的末尾,不会覆盖文件中已有的内容
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);

 调用方法将数据写入到指定文件中

        outputStreamWriter.write("HelloWorld");

5、FileWriter

创建对象

FileWriter fileWriter = new FileWriter("F:/Demo/cc.txt",true);

写入数据

            fileWriter.write("Java2322");
            System.out.println("数据写入完毕");

6、BufferedWriter

 创建对象

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("F:/Demo/ee.txt"));
1>.witer() 写入
2>.newLine() 换行
            bufferedWriter.write("大湖名城");
            //换行
            bufferedWriter.newLine();
            bufferedWriter.write("包河看河");
            bufferedWriter.newLine();
            bufferedWriter.write("瑶海看海");
            bufferedWriter.newLine();
            bufferedWriter.write("滨湖看湖");

            写操作,会将数据写入缓存中,还没有写到文件中, 需要使用flush()方法将数据强制写入到文件中

bufferedWriter.flush();

7、实例:替换pet. template文件中的某些内容

        FileReader fileReader = new FileReader("F:/Demo/pet. template");

        System.out.print("替换前:");
        //读取数据
       int num;
       StringBuffer stringBuffer = new StringBuffer("");
       while((num=fileReader.read())!=-1){
//           System.out.print((char)num);
           //每读到一个数据,就将其追加到一个字符串对象中
           stringBuffer.append((char)num);
       }

//        System.out.println(stringBuffer);


       //接下来进行替换,将StringBuffer里的某些内容替换成其他内容,查询API发现,StringBuffer里的替换方法不太好实现,String类的替换方法更好实现,所以,先将StringBuffer对象转换成StringBuffer对象
        String str =stringBuffer.toString();
        System.out.println(str);
//        String str2 =str.replace("{name}","欧欧");
//        String str3 =str2.replace("{type}","狗狗");
//        String str4 =str3.replace("{master}","李伟");
        String str4 =str.replace("{name}","欧欧").replace("{type}","狗狗").replace("{master}","李伟");
        System.out.println("替换后:"+str4);

        //将str4写入文件中
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("F:/Demo/pet.txt"));
        bufferedWriter.write(str4);
        //记得刷新缓存中的数据
        bufferedWriter.flush();
        System.out.println("数据写入完毕");

8、DataInputStream  和  DataOutputStream

1>DataInputStream
        //创建DataInputStream类对象
        InputStream inputStream = new FileInputStream("F:/Demo/girl.jpg");
        DataInputStream dataInputStream = new DataInputStream(inputStream);
2>DataOutputStream
        //创建DataOutputStream类对象
        OutputStream outputStream = new FileOutputStream("F:/Demo/girlfriend.jpg");
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
3>循环读取数据
       int num;
       while((num=dataInputStream.read())!=-1){
           //输出读取的二进制数据没有意义,可以进行写入文件操作
//           System.out.println(num);
           dataOutputStream.write(num);
       }

9、ObjectInputStream     和    ObjectOutputStream

        //创建Student类对象
        Student student1 = new Student("张三",22);


        //需求:将上面创建的Student类对象写入到F盘Demo文件夹里的student.txt文件中

注意:在Student类中对属性操作

private transient int age;

transient关键字可以让属性不进行序列化操作,在反序列时,获取的数据就是对应的默认值

 这里默认值例如:int类型是0,String类型是null

 

1> ObjectOutputStream

创建对象

        OutputStream outputStream = new FileOutputStream("F:/Demo/student2.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

 

 

2> ObjectInputStream

创建对象

        InputStream inputStream = new FileInputStream("F:/Demo/student2.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值