• Java-day13(IO流)


    IO流

    凡是与输入,输出相关的类,接口等都定义在java.io包下
    在这里插入图片描述

    1.File类的使用

    • File类可以有构造器创建其对象,此对象对应着一个文件(.txt,.avi,.doc,.mp3等)或文件目录

    • File类对象是与平台无关的

    • File中的方法仅涉及到如何创建,删除,重命名等操作,不涉及文件内容的修改(需IO流来操作)

    • File类对象常作为io流的具体类的构造器的形参

    常见的方法
    在这里插入图片描述
    熟练掌握红色标记的方法
    例:

    import java.io.File;
    import java.sql.Date;
    
    import org.junit.Test;
    public class test10{
        @Test
        public void test1(){
            //绝对路径
            File f1 = new File("C:/Users/Cat God 007/Desktop/hello.txt"); //文件
            File f2 = new File("C:/Users/Cat God 007/Desktop");//文件目录
            //相对路径
            File f3 = new File("hello.txt");
    
            System.out.println("=============访问文件名================");
            System.out.println(f3.getName());//返回文件名          
            System.out.println(f3.getPath());//返回文件路径
            System.out.println(f3.getAbsoluteFile());//返回文件的绝对路径
            System.out.println(f3.getParent());//返回上一级文件目录
            System.out.println(f3.getAbsolutePath());//返回完整的文件路径
    
            System.out.println("=============================");
    
            System.out.println(f2.getName());//返回文件目录名
            System.out.println(f2.getPath());//返回文件目录路径
            System.out.println(f2.getAbsoluteFile());//返回文件目录的绝对路径
            System.out.println(f2.getParent());//返回上一级文件目录
            System.out.println(f2.getAbsolutePath());//返回完整的文件目录路径
    
            System.out.println("============文件检测=========");
            System.out.println(f1.exists());//检测文件是否存在
            System.out.println(f1.canRead());//检测文件是否可读
            System.out.println(f1.canWrite());//检测文件是否可写
            System.out.println(f1.isFile());//检测此对象是否不是文件
            System.out.println(f1.isDirectory());//检测此对象是否不是文件目录
            
            System.out.println("============获取常规文件信息=========");
    
            System.out.println(new Date(f1.lastModified()));//获取文件最后修改时间
            System.out.println(f1.length());//获取文件大小
        }
    
        @Test
        public void test2(){
            File f1 = new File("C:/Users/Cat God 007/Desktop/hello.txt"); 
            File f2 = new File("C:/Users/Cat God 007/Desktop/test/tes1-test9");
            System.out.println(f1.delete());//删除文件
    
            if(!f1.exists()){
                boolean b1 = f1.createNewFile();//创建文件
                System.out.println(b1);
            }
            if(!f2.exists()){
                boolean b2 = f2.mkdir();//mkdirs()可以递归创建文件夹,mkdir只创建最后的文件目录,若它上层没有创建,则它也不会创建
                System.out.println(b2);
            }
    
            File f3 = new File("C:\\Users\\Cat God 007\\Desktop\\javacode\\day13");
            String[] list = f3.list();
            for(int i = 0;i < list.length;i++){
                System.out.println(list[i]);//以String方式读取出f3下的文件
            }
    
            
            File[] files = f3.listFiles();
            for(int i = 0;i < files.length;i++){
                System.out.println(files[i].getName());//以文件方式读取出f3下的文件
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    2.IO流原理及其分类

    • IO流用来处理设备之间的数据传输
    • 按数据单位可分为:字节流(8bit)字符流(16bit)
    • 按流的流向可分为:输入流输出流
    • 按流的角色可分为:节点流(直接作为于文件),处理流
    抽象基类字节流字符流
    输入流InputStreamReader
    输出流OutputStreamWriter
    	IO流设计40多个类,都是从以上4个抽象基类派生
    	由这四个类派生出的子类名称都是以其父类名作为子类名后缀
    
    • 1
    • 2

    IO流体系

    在这里插入图片描述

    • 访问文件的类也被称为节点流,文件流,其他类被称为处理流

    3.文件流

    FileInputStream

    例:

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import org.junit.Test;
    
    public class test11{
    
    @Test
    //读取硬盘文件内容到程序中,使用FileInputStream(读取的文件一定要存在,否则会报文件找不到的异常)
    public void test1()throws Exception{
        //1.创建Filen类型的对象
        File file = new File("hello.txt");
        //2.创建FileInputStream类型的对象
        FileInputStream files = new FileInputStream(file);      
        //3.调用FileInputStream的方法,实现file文件的读取
        //read():读取文件的一个字节,当执行到文件结尾时,返回-1
        //方式一
        int b = files.read();
        while(b != -1){
            System.out.println((char)b);//int转字符(否则打印出来的是对应的Ascll码)
            b = files.read();
        }
        //方式二
        int c;
        while((c = files.read()) != -1){
            System.out.println((char)c);
        }
        //4.关闭相应的流
        files.close();
    }
        @Test
        //测试test1的优化,确保每次流都能被关闭
        public void test2(){
            
        FileInputStream files = null;
        try {
            File file = new File("hello.txt");
            files = new FileInputStream(file);
            int c;
            while((c = files.read()) != -1){
                System.out.println((char)c);
                }
            } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(files != null){
            try{
            files.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
    }
        @Test
        public void test3(){
        FileInputStream files = null;
        try{
        File file = new File("hello.txt");
        files = new FileInputStream(file);
    
        byte[] b = new byte[5];//将读取到的数据写入数组中
        int len;//每次读入到byte中的字节长度
        while((len = files.read(b)) != -1){
            // 方式一:运行for循环实现遍历输出
            // 成功案例:
            for(int i = 0;i < len;i++){
                System.out.print((char)b[i]);
            }
            //错误案例:使用b.length时,在读取到最后(此时只读取了1个元素),但依旧会传入5个元素的数组{1个新元素+4个旧元素}
            // for(int i = 0;i < b.length;i++){
            //     System.out.print((char)b[i]);
            // }
    
            //方式二:运行String构造器实现遍历输出
            // String str = new String(b, 0, len);
            // System.out.println(str);
    
        }}catch(IOException e){
            e.printStackTrace();
        }finally{
            if(files != null){
            try{
                files.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    FileOutputStream

    简单编写

    import java.io.File;
    import java.io.FileOutputStream;
    import org.junit.Test;
    
    public class test12{
        @Test
        public void testFileOutputSteam(){
            //1.创建要写入文件的文件路径的File对象,此文件路径可以不存在(会自动创建),若存在,就会用新写入的数据覆盖原来的数据
            File file = new File("hello1.txt");
            //2.创建FileOutputStream对象,将之前的File对象作形参传入FileOutputStream的构造器中
            FileOutputStream f = null;
            try{   
                f = new FileOutputStream(file);
                //3.写入数据
                f.write(new String("I Love China").getBytes());//这里用到了字符串转字节数组
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                //关闭输出流
                if(f != null){
                try{
                    f.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    练习:编写非文本文件复制的方法
    主要实现

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import org.junit.Test;
    
    public class test12{
        @Test
        //从硬盘中读入数据,将此数据写入到另一位置(相当文件复制)
        public void testFileInputOutputSteam(){
            //1.提供读,写的文件路径
            File file1 = new File("C:\\Users\\Cat God 007\\Desktop\\t1.jpg");
            File file2 = new File("C:\\\\Users\\\\Cat God 007\\\\Desktop\\\\tt.jpg");
            //2.提供读,写流
            FileOutputStream fos = null;
            FileInputStream fis = null;
            try{ 
                fis = new FileInputStream(file1);
                fos = new FileOutputStream(file2);
                //3.实现文件复制
                byte [] b = new byte[20];
                int len;
                while ((len = fis.read(b)) != -1) {
                    fos.write(b,0,len);                
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                //4.关闭读,写流
                if(fos != null){
                    try{
                        fos.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
                if(fis != null){
                    try{
                        fis.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
    
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    最后包装成方法,并进行测试

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    public class test12{
        public static void main(String[] args) {  
            testFileInputOutputSteam("C:\\Users\\Cat God 007\\Desktop\\t1.jpg", "C:\\Users\\Cat God 007\\Desktop\\tt1.jpg");
        }
        public static void testFileInputOutputSteam(String src,String dest){
            File file1 = new File(src);
            File file2 = new File(dest);
            
            FileOutputStream fos = null;
            FileInputStream fis = null;
            try{
                fis = new FileInputStream(file1);
                fos = new FileOutputStream(file2);
               
                byte [] b = new byte[20];
                int len;
                while ((len = fis.read(b)) != -1) {
                    fos.write(b,0,len);                
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                
                if(fos != null){
                    try{
                        fos.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
                if(fis != null){
                    try{
                        fis.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
    
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    FileReader,FileWriter(字符流)
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import org.junit.Test;
    
    public class test13{
        //使用FileReader,FileWriter可以实现文本文件的复制
       @Test
       public void testFileReaderWriter(){    
        FileReader fr = null;
        FileWriter fw = null; 
        try{
            File src = new File("hello.txt");//读
            File desc = new File("hello1.txt");//写
            fr = new FileReader(src);
            fw = new FileWriter(desc);
           
            char[] c = new char[20];
            int len;
            while ((len = fr.read(c)) != -1) {
                fw.write(c,0,len);                
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            
            if(fr != null){
                try{
                    fr.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(fw != null){
                try{
                    fw.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 文本文件用字符流,非文本文件(视频文件,音频文件,图片)用字节流,效率较高

    4.缓冲流(主要使用)

    • 可以提高处理数据的效率

    • 每次处理完后,都需要刷新(flush())数组,方便下次元素不够写入的情况

    使用 BufferedInputStream,BufferedOutputStream 实现非文本文件的复制

    例:

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import org.junit.Test;
    
    public class test14{
        @Test
        public void testBufferedInputOutputStream(){
            BufferedInputStream bis = null;
            BufferedOutputStream  bos = null;
            try{            
            //1.提供读写文件
            File file1 = new File("C:\\Users\\Cat God 007\\Desktop\\t1.jpg");
            File file2 = new File(".\\1.jpg");
            //2.创建相应的节点流
            FileInputStream fis = new FileInputStream(file1);
            FileOutputStream fos = new FileOutputStream(file2);
            //3.将创建的节点流的对象作为形参传递给缓冲流的构造器中
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //4.实现文本文件
            byte[] b = new byte[1024];
            int len;
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
                bos.flush();//刷新一下
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //5.关闭相应的流
            if(bis != null){
                try{
                bis.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(bos != null){
                try{
            bos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
        }}
    }
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    使用BufferedReader,BufferedWriter实现文本文件的复制
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import org.junit.Test;
    
    public class test{
    // BufferedReader()的readLine()方法(一行一行读)
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import org.junit.Test;
    
    public class test14{
        @Test
        public void testBufferedReader(){
            BufferedReader br = null;
            BufferedWriter bw = null;
            try{        
            File file = new File("hello.txt");
            File file1 = new File("hell1o.txt");
            FileReader fr = new FileReader(file);
            FileWriter fw = new FileWriter(file1);
            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);
            // char[] c = new char[1024];
            // int len;
            // while ((len = br.read(c)) != -1) {
            //     String str = new String(c, 0, len);
            //     System.out.print(str);
            // }
            String str;
            while ((str = br.readLine()) != null) {
                //System.out.println(str);
                bw.write(str + "\n");
                //bw.newLine();//换行
                bw.flush();
            }
        }catch(Exception e){
                e.printStackTrace();
            }finally{
                if(bw != null){
                    try{
                    bw.close();
                 }catch(Exception e){
                    e.printStackTrace();
                 }
                }
                if(br != null){
                    try{
                    br.close();
                 }catch(Exception e){
                    e.printStackTrace();
                 }
                }
        }}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    5.转换流

    • 提供在字节流和字符流之间的转换

    • 字节流中的数据都是字符时,转换成字符流操作更高效

    • 编码(字符串====>字节数组),解码(字节数组====>字符串)

    • 提供两个转换流InputStreamReader(解码),OutputStreamWriter(编码)

    例:

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    
    import org.junit.Test;
    
    public class test16{
        @Test
        public void test1(){
            
            BufferedReader br = null;
            BufferedWriter bw = null;
            try{ 
            //解码(字节数组====>字符串)
            File file = new File("hello.txt");
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            br = new BufferedReader(isr);
            //编码(字符串====>字节数组)
            File file1 = new File("hello123.txt");
            FileOutputStream fos = new FileOutputStream(file1);
            OutputStreamWriter isw = new OutputStreamWriter(fos, "UTF-8");
            bw = new BufferedWriter(isw);
            String str;
            while ((str = br.readLine()) != null) {
                //System.out.println(str);
                isw.write(str + "\n");
                //bw.newLine();//换行
                isw.flush();
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(bw != null){
                try{
                    bw.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
    
            if(br != null){
                try{
                    br.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    6.标准的输入输出流

    • 标准的输出流:System.out
    • 标准的输入流:System.in

    例:
    在这里插入图片描述

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import org.junit.Test;
    
    public class test16{
        @Test
        public void test(){
            BufferedReader br = null;
            try{   
            InputStream is = System.in;//接受传入的字节流
            InputStreamReader isr = new InputStreamReader(is); //字节转字符
            br = new BufferedReader(isr); //包装成带缓冲的字符流
            String str;
            while(true){
                System.out.println("请输入字符串:");
                str = br.readLine();
                //忽略大小写
                if(str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")){
                    break;
                }
                String str1 = str.toUpperCase();//转化成大写
                System.out.println(str1);
            }}catch(IOException e){
                e.printStackTrace();
            }finally{
                if(br != null){
                try{
                    br.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    练习

    在一个目录下创建test.txt文件,并写入以下内容:

    云计算是一个比较庞大的概念,入门云计算,首先要从掌握基本概念和基础知识开始,然后通过掌握完全面向云计算的特定供应商的平台或技术等重要领域来增强其专业知识水平,
    这样可以更快的学好云计算。你需要学习这些知识:
    计算机与网络的基础知识
    安全基础知识
    编程语言基础
    脚本语言
    linux基础知识
    分布式系统
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    读取test.txt文件的内容,并打印出来
    复制test.txt文件为cloudcompute.txt文件

    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    
    import org.junit.Test;
    
    public class test17{
        @Test
        //字节流写入文本文件数据
        public void test1(){
        BufferedOutputStream bos = null;
        try{      
        File file = new File("C:\\Users\\Cat God 007\\Desktop\\test.txt");
        FileOutputStream fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        String str = "\u4E91\u8BA1\u7B97\u662F\u4E00\u4E2A\u6BD4\u8F83\u5E9E\u5927\u7684\u6982\u5FF5\uFF0C\u5165\u95E8\u4E91\u8BA1\u7B97\uFF0C\u9996\u5148\u8981\u4ECE\u638C\u63E1\u57FA\u672C\u6982\u5FF5\u548C\u57FA\u7840\u77E5\u8BC6\u5F00\u59CB\uFF0C\u7136\u540E\u901A\u8FC7\u638C\u63E1\u5B8C\u5168\u9762\u5411\u4E91\u8BA1\u7B97\u7684\u7279\u5B9A\u4F9B\u5E94\u5546\u7684\u5E73\u53F0\u6216\u6280\u672F\u7B49\u91CD\u8981\u9886\u57DF\u6765\u589E\u5F3A\u5176\u4E13\u4E1A\u77E5\u8BC6\u6C34\u5E73\uFF0C\r\n" + //
                "\u8FD9\u6837\u53EF\u4EE5\u66F4\u5FEB\u7684\u5B66\u597D\u4E91\u8BA1\u7B97\u3002\u4F60\u9700\u8981\u5B66\u4E60\u8FD9\u4E9B\u77E5\u8BC6\uFF1A\r\n" + //
                "\u8BA1\u7B97\u673A\u4E0E\u7F51\u7EDC\u7684\u57FA\u7840\u77E5\u8BC6\r\n" + //
                "\u5B89\u5168\u57FA\u7840\u77E5\u8BC6\r\n" + //
                "\u7F16\u7A0B\u8BED\u8A00\u57FA\u7840\r\n" + //
                "\u811A\u672C\u8BED\u8A00\r\n" + //
                "linux\u57FA\u7840\u77E5\u8BC6\r\n" + //
                "\u5206\u5E03\u5F0F\u7CFB\u7EDF";
        bos.write(str.getBytes());
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(bos != null){
                try{
                     bos.flush();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        }
        @Test
        //字符流写入文本文件数据
        public void test2(){
             BufferedWriter bw = null;
        try{
        bw = new BufferedWriter(new FileWriter(new File("C:\\Users\\Cat God 007\\Desktop\\test.txt")));
    
        String str = "\u4E91\u8BA1\u7B97\u662F\u4E00\u4E2A\u6BD4\u8F83\u5E9E\u5927\u7684\u6982\u5FF5\uFF0C\u5165\u95E8\u4E91\u8BA1\u7B97\uFF0C\u9996\u5148\u8981\u4ECE\u638C\u63E1\u57FA\u672C\u6982\u5FF5\u548C\u57FA\u7840\u77E5\u8BC6\u5F00\u59CB\uFF0C\u7136\u540E\u901A\u8FC7\u638C\u63E1\u5B8C\u5168\u9762\u5411\u4E91\u8BA1\u7B97\u7684\u7279\u5B9A\u4F9B\u5E94\u5546\u7684\u5E73\u53F0\u6216\u6280\u672F\u7B49\u91CD\u8981\u9886\u57DF\u6765\u589E\u5F3A\u5176\u4E13\u4E1A\u77E5\u8BC6\u6C34\u5E73\uFF0C\r\n" + //
                "\u8FD9\u6837\u53EF\u4EE5\u66F4\u5FEB\u7684\u5B66\u597D\u4E91\u8BA1\u7B97\u3002\u4F60\u9700\u8981\u5B66\u4E60\u8FD9\u4E9B\u77E5\u8BC6\uFF1A\r\n" + //
                "\u8BA1\u7B97\u673A\u4E0E\u7F51\u7EDC\u7684\u57FA\u7840\u77E5\u8BC6\r\n" + //
                "\u5B89\u5168\u57FA\u7840\u77E5\u8BC6\r\n" + //
                "\u7F16\u7A0B\u8BED\u8A00\u57FA\u7840\r\n" + //
                "\u811A\u672C\u8BED\u8A00\r\n" + //
                "linux\u57FA\u7840\u77E5\u8BC6\r\n" + //
                "\u5206\u5E03\u5F0Fw\u7CFB\u7EDF";
        bw.write(str);
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(bw != null){
                try{
                     bw.flush();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        }
        @Test
        //字符流输出文本文件数据
        public void test3(){
            BufferedReader br = null;
            try{
                br = new BufferedReader(new FileReader("C:\\Users\\Cat God 007\\Desktop\\test.txt"));
    
                String str;
                while((str = br.readLine()) != null){
                    System.out.println(str);
                }
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(br != null){
                try{
                    br.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    
        }
        @Test
        //字符流实现复制
        public void test4(){
            BufferedWriter bw = null;
            BufferedReader br = null;
            try{
                br = new BufferedReader(new FileReader("C:\\Users\\Cat God 007\\Desktop\\test.txt"));
                bw = new BufferedWriter(new FileWriter("C:\\Users\\Cat God 007\\Desktop\\cloudcompute.txt"));
                String str;
                while((str = br.readLine()) != null){
                    bw.write(str + "\n");
                }            
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(bw != null){
                    try{
                        bw.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
                if(br != null){
                    try{
                        br.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
                
            }
    
        }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129

    7.打印流

    • PrintStream:字节流 printWriter:字符流

    例:

    public class test18{
        @Test
        //打印流
        public void printStreamTest(){
            FileOutputStream fos = null;
            try{    
                fos = new FileOutputStream("C:\\Users\\Cat God 007\\Desktop\\test.txt");
            }catch(IOException e){
                e.printStackTrace();
            }
            //创建打印输出流,设置为自动刷新模式(写入换行符就或字节'\n'时都会刷新输出缓冲区)
            PrintStream ps = new PrintStream(fos,true);
            if(ps != null){//把标准输出流改成文件
                System.setOut(ps);//修改输出打印的位置为ps
            }
            for(int i = 0;i < 255;i++){
                System.out.print((char)i);
                if(i % 50 == 0){//每50数据一行
                    System.out.println();//换行
                }
            }
            ps.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    8.数据流

    在这里插入图片描述

    • 用来处理基本数据类型,String,字节数组的数据

    例:

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    
    import org.junit.Test;
    
    public class test19{
        @Test
        //数据流写入
        public void testData(){
             DataOutputStream dos = null;
             try {          
             FileOutputStream fos = new FileOutputStream("C:\\Users\\Cat God 007\\Desktop\\test.txt");
             dos = new DataOutputStream(fos);
    
             dos.writeUTF("你好");
             dos.writeInt(467876543);
             dos.writeDouble(1289.789);
             dos.writeBoolean(true);
             }catch(IOException e){
                e.printStackTrace();
             }finally{
                if(dos != null){
                    try {
                        dos.close();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
        }
            }
        }
        @Test
        //数据流读取
        public void testData1(){
            DataInputStream dis = null;
            try {   
                dis = new DataInputStream(new FileInputStream("C:\\Users\\Cat God 007\\Desktop\\test.txt"));
                String str = dis.readUTF();
                System.out.println(str);
                int i = dis.readInt();
                System.out.println(i);
                double d = dis.readDouble();
                System.out.println(d);
                boolean b = dis.readBoolean();
                System.out.println(b);
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(dis != null){
                    try {
                        dis.close();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    9.对象流

    ObjectOutputStream 和 ObjectInputStream

    • 用于存储和读取对象的处理流,可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来

    • 序列化(Serialize):用 ObjectOutputStream 类将Java对象写入IO流中
      在这里插入图片描述

    • 反序列化(Deserialize):用 ObjectInputStream 类从IO流中恢复该Java对象

    • ObjectOutputStream 和
      ObjectInputStream不能序列化static和transient(短暂的)修饰的成员变量

    例:
    i

    mport java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import org.junit.Test;
    
    public class test20{
        @Test
        // 反序列化--ObjectInputStream
        public void testObjectInputStream(){
            ObjectInputStream ois = null;
            try {     
                ois = new ObjectInputStream(new FileInputStream("C:\\\\Users\\\\Cat God 007\\\\Desktop\\\\test.txt"));
                
                Person p1 = (Person)ois.readObject();//读取一个对象
                System.out.println(p1.toString());//打印一个对象
                Person p2 = (Person) ois.readObject();//读取对象
                System.out.println(p2);//打印对象
    
            }catch (IOException e){
                e.printStackTrace();
            }finally{
                if(ois != null){
                    try{
                        ois.close();
                    }catch (IOException e){
                        e.printStackTrace();
                }
            }
            }
        }
        @Test
        //对象序列化---ObjectOutputStream
        public void testObjectOutputStream(){
            Person p1 = new Person("张三", 20,new Pet("张二"));
            Person p2 = new Person("李四", 21,new Pet("李三"));
    
            ObjectOutputStream oos = null;
            try{
            oos = new ObjectOutputStream(new FileOutputStream("C:\\\\Users\\\\Cat God 007\\\\Desktop\\\\test.txt"));
            oos.writeObject(p1);
            oos.flush();
            oos.writeObject(p2);
            oos.flush();       
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    if(oos != null){
                    try {
                        oos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    }
                }
        }
    }
    /*
     * 实现序列化的类:
     * 1.此类可序列化,需要此类实现Serializable接口
     * 2.此类可序列化,需要类的属性同样实现Serializable接口
     * 3.版本号:凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量,表明类的不同版本间的兼容性,如果没有定义,那在运行时会自动生成,如果源码修改,版本号(自动生成的)可能会变化
     * 如:private static final long serialVersionUID = 1234678876543L;   
     */
    class Person implements Serializable{ 
        private static final long serialVersionUID = 12343128876543L; 
        String name;
        Integer age;
        Pet pet;
        public Person(String name, Integer age,Pet pet) { 
            this.name = name;
            this.age = age; 
            this.pet = pet;
    
        }
        @Override
        public String toString() { 
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age + '\'' +
                    ", pet=" + pet + '\'' +
                    '}';
        }
    }
    class Pet implements Serializable{
        String name;
        public Pet(String name) {
            this.name = name;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92

    10.随机存取文件流

    • RandomAccessFile类支持"随机访问"的方式,程序可以直接跳到文件的任意地方来读,写文件

      • 可以向已存在的文件后追加内容

      • 支持只访问文件的部分内容

    • RandomAccessFile对象包含一个记录指针,用于标示当前读写处的位置。RandomAccessFile类类对象可以自由移动记录指针

      • long getFilePointer():获取文件记录指针的当前位置

      • void seek(long pos):将文件记录指针定位到pos位置
        在这里插入图片描述

    例:

    import java.io.RandomAccessFile;
    
    import org.junit.Test;
    
    public class test21{
        @Test
        //进行文件的读,写
        public void test(){
            RandomAccessFile raf1 = null;
            RandomAccessFile raf2 = null;
            try{    
                raf1 = new RandomAccessFile("hello.txt","r");
                raf2 = new RandomAccessFile("hello1.txt","rw");
    
                byte[] b = new byte[4];
                int len;
                while((len = raf1.read(b))!=-1){
                    raf2.write(b,0,len);
                    }
                }catch(Exception e){{
                    e.printStackTrace();
                }
            }finally{
                if(raf2 != null){
                    try{
                        raf2.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                    }
                if(raf1 != null){
                    try{
                        raf1.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
                }
            }
        }
    
        @Test
        //在指定位置进行文件的读写,实际上实现的是覆盖的效果
        public void test1(){
            RandomAccessFile raf = null;
            try{
                raf = new RandomAccessFile("hello.txt","rw");
                raf.seek(3);//把指针调到第三个的位置
                raf.write("123456789".getBytes());
                
            }catch(Exception e) {
                e.printStackTrace();
            }finally{
                if(raf != null){
                    try{
                raf.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                    }
            }
        }
    
        @Test
        //实现在指定位置的插入效果
        public void test2(){
            RandomAccessFile raf = null;
            try{
                raf = new RandomAccessFile("hello.txt","rw");
                raf.seek(3);
                byte[] b = new byte[10];
                int len;
                StringBuffer sb = new StringBuffer();//可变的字符序列,相当于String
                while((len = raf.read(b)) != -1){
                   sb.append(new String(b,0,len));
                    }
                raf.seek(3);//把指针调到第三个的位置
                raf.write("123456789".getBytes());//写入要插入的内容
                raf.write(sb.toString().getBytes());//写入原来的后面字符
    
                
            }catch(Exception e) {
                e.printStackTrace();
            }finally{
                if(raf != null){
                    try{
                raf.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                    }
            }
    
        }
        @Test
        //实现在指定位置的插入效果(在test2的基础上进行优化,使之更通用)
        public void test3(){
            RandomAccessFile raf = null;
            try{
                raf = new RandomAccessFile("hello.txt","rw");
                raf.seek(3);
                String str = raf.readLine();//读取出要插入处之后的所有字符
                // long l = raf.getFilePointer();//获取当前指针的位置
                // System.out.println(l);//12
    
                 raf.seek(3);//把指针调到第三个的位置
                 raf.write("123456789".getBytes());//写入要插入的内容
                 raf.write(str.getBytes());//写入原来的后面字符
    
                
            }catch(Exception e) {
                e.printStackTrace();
            }finally{
                if(raf != null){
                    try{
                raf.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                    }
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123

    IO流练习
    在这里插入图片描述

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class test1 {
    
    	public static void main(String[] args) {   
    		test1 t = new test1();
    		System.out.println("请输入一个字符串:");
    		String str = t.nextString();
    		System.out.println(str);
    		
    		int j = t.nextInt();
    		System.out.println(j + 20);
    		
    
    	}
    	public String nextString() {
    		InputStreamReader isr = new InputStreamReader(System.in);
    		BufferedReader br = new BufferedReader(isr);
    		String str = null;
    		try {
    			str = br.readLine();
    			
    		}catch(IOException e) {
    			e.printStackTrace();
    		}
    		return str;
    	}
    	public int nextInt() {
    		return Integer.parseInt(nextString());
    	}
    	public boolean nextBoolean() {
    		return Boolean.parseBoolean(nextString());
    	}
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    感谢大家的支持,关注,评论,点赞!
    参考资料:
    尚硅谷宋红康20天搞定Java基础下部

  • 相关阅读:
    事物/现象/事情/东西/情况/表象
    vscode 连接 GitHub
    android-handler
    数据结构——线性表之顺序表
    1387. 将整数按权重排序
    C++入门学习3-指针与字符数组,函数,指针数组
    Spark Dataset 输出成csv文件
    pytorch DistributedDataParallel 分布式训练踩坑记录
    Java代码审计15之Apache log4j2漏洞
    安卓去除开屏广告
  • 原文地址:https://blog.csdn.net/weixin_51202460/article/details/132590661