Java高级之---IO流的使用

IO流的使用

一、File类

1.File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)

2.File类声明在java.io下

3.File类中涉及到关于文件的目录和文件的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入和读取文件的操作,如果要适用读取和写入等操作,必须使用IO流来完成。

4.后续File类的对象常用来作为参数传递到流的构造器中,指明读取或写入的"终点"。

File类的使用

1.如何创建File类的实例

File(String filePath)

File(String filPath,String childPath)

File(File parentFile,String childPath)

   //构造器一
       File file = new File("hello.txt");//相对于当前文件夹module
       File file1 = new File("D:\\io\\hello1.txt");

       //构造器二
//        File file2 = new File(tring filPath,String childPath)

       //构造器三
       File file3 = new File(file1, "hello2.txt");
   }

2.路径问题
相对路径:相对于某个路径下,指明的路径
绝对路径:包含盘符在内的文件或文件目录的路径

3.路径分隔符
windows:\
unix:/

1.在IDEA中,使用JUnit单元测试方法,相对路径为当前的module下,main()方法中测试,相对路径在Project下
2.在Eclipse下,不管是单元测试还是main()中,相对路径都是当前的Project下。

File的获取功能

public String getAbsolutePath():获取绝对路径
public String getPath():获取路径
public String getName():获取名称
public String getParent():获取上层文件的目录路径,若无,返回null
public long length():获取文件长度(即:字节数),不能返会目录的长度
public long lastModified():获取最后一次的修改时间,毫秒值
下面的两个方法适用于文件目录
public String[] list():获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles(): 获取指定目录下的所有文件或者文件目录的File数组

  File file1 = new File("hello.txt");
        File file2 = new File("D:\\io\\hello1.txt");

        //如果硬盘中真实存在hello.txt文件,那么值将发生改变

        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getPath());//hello.txt
        System.out.println(file1.getName());//hello.txt
        System.out.println(file1.getParent());//null
        System.out.println(file1.length());//0-->10(字节)
        System.out.println(file1.lastModified());//0-->1586871494015(毫秒值)

        System.out.println();

        System.out.println(file2.getAbsolutePath());
        System.out.println(file2.getPath());
        System.out.println(file2.getName());//hello1.txt
        System.out.println(file2.getParent());
        System.out.println(file2.length());//0
        System.out.println(file2.lastModified());//0

如果文件目录不存在,空指针异常

 File file = new File("D:\\java\\idea\\JavaSenior");

        String[] list = file.list();

        for (String str : list) {
            System.out.println(str);
        }

        File[] files = file.listFiles();//获取到该目录下的所有绝对路径
        for (File f : files) {
            System.out.println(f);
        }
File类的重命名功能

public boolean renameTo(File dest):
//想要为true,file必须真实存在,且file1不能存在

 File file = new File("hello.txt");
           File file1 = new File("D:\\\java\\idea\\JavaSenior\\hi.txt");
           boolean b = file.renameTo(file1);
           System.out.println(b);
File类的判断功能

public boolean isDirectory():判断是否是文件目录

public boolean isFile():判断是否是文件

public boolean exists():判断是否存在

public boolean canRead():判断是否可读

public boolean canWrite():判断是否可写

public boolean isHidden():判断是否隐藏
实例:

  File file = new File("hello.txt");

        System.out.println(file.isDirectory());
        System.out.println(file.isFile());
        System.out.println(file.exists());
        System.out.println(file.canRead());
        System.out.println(file.canWrite());
        System.out.println(file.isHidden());
File类的创建功能

public boolean createNewFile():创建文件。若文件存在,则不创建,返回false

public boolean mkdir():创建文件目录。如果此文件目录存在,就不创建了。
如果此文件目录的上层目录不存在,也不创建。

public boolean mkdirs():创建文件目录。如果上层文件不存在,一并创建

注意:如果你创建的文件或文件目录没有写盘符路径,那么,默认在项目的路径下

File类的删除功能

public Boolean delete():删除文件或文件夹
注意:java中的删除不走回收站
要删除一个文件目录,请注意,该文件目录内不能包含文件或文件目录

    @Test
   public void test5() throws IOException {
       File file = new File("hello1.txt");
       if (!file.exists()){
           file.createNewFile();
           System.out.println("创建成功");
       }else {//文件存在
           file.delete();
           System.out.println("删除成功");
       }
   }
   @Test
   public void test6(){
       //文件目录创建
       File file = new File("D:\\java\\idea\\JavaSenior\\js");

       boolean b = file.mkdir();
       if (b){
           System.out.println("创建成功");
       }
   }
二、流的分类
IO流的体系分类

在这里插入图片描述
1.操作的数据单位:字节流、字符流

2.数据的流向:输入流、输出流

3.流的角色:节点流、处理流

4.流的体系结构
①抽象基类
InputStream
OutPutStream
Reader
Writer

② 节点流(文件流)
FileInputStream (read(byte[] buffer))
FileOutPutStream (write(byte[] buffer,0,len))
FileReader (read(char[] cbuf))
FileWriter (write(char[] cbuf,0,len))

③ 缓冲流(处理流的一种)
BufferedInputStream (read(byte[] buffer))
BufferedOutPutStream (write(byte[] buffer,0,len))/flush()
BufferedReader (read(char[] cbuf))/readLine()
BufferedWriter (write(char[] cbuf,0,len))/flush()

1.将当前module下的hello.txt文件内容读入到程序中,并输出到控制台

1.read():返回读入的一个字符,如果达到文件的末尾,返回-1

2.异常的处理:为了保证流的资源一定可以执行关闭操作,需要使用try-catch-finally处理异常

3.读入的文件,一定要存在,否则就会出现异常(FileNotFoundException)

 public static void main(String[] args) {
       File file = new File("hello.txt");//相对路径,相较于当前工程下
   }

在单元测试方法中使用(在以下所以的hello.txt在里面随意赋一些值)

 @Test
   public void testFileReader(){
       FileReader fileReader = null;
       try {
           //1.实例化file类的对象,指明要操作的文件
           File file = new File("hello.txt");//相对路径,相较于当前module
           //2.提供具体的流,抛出异常,文件找不到的异常(FileNotFoundException)
           fileReader = new FileReader(file);
           //3.数据的读入过程
           //read():返回读入的一个字符,如果达到文件的末尾,返回-1
           //方式一
//        int read = fileReader.read();
//        while (read != -1){
//            System.out.println((char) read);
//            read = fileReader.read();
//        }
           //发生二
           int data;
           while ((data = fileReader.read()) != -1){
               System.out.print((char) data + "\t");
           }
       } catch (IOException e) {
           e.printStackTrace();
       }finally {
           //4.流的关闭操作
           try {
              if (fileReader!=null){
                  fileReader.close();
              }
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }
2.对read方法的操作升级:使用read的重载方法
 FileReader fileReader = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");
            //2.FileReader流的实例化
            fileReader = new FileReader(file);
            // 3.读入的操作
            //read(char[] c):返回每次读入c数组中的字符的个数,如果达到文件末尾,返回-1
            char[] chars = new char[5];
            int len;
            while ((len = fileReader.read(chars))!=-1){
                //方式一
                //错误的
//                for (int i = 0;i < chars.length;i++ ){
//                    System.out.print(chars[i]);
//                }
                //正确的
//                for (int i = 0;i < len;i++ ){
//                    System.out.print(chars[i]);
//                }
                //方式二
                //错误的
//                String str = new String(chars);
//                System.out.println(str);
                //正确的
                String str = new String(chars,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileReader!=null){
                //4.资源的关闭
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
3.从内存中写出数据到硬盘的文件里

①.输出操作,对应的file文件可以不存在,如果不存在,会自动创建文件
②.如果存在:

如果流使用的构造器是:FileWriter(file,false);/FileWriter(file);表示对原有文件进行覆盖

如果流使用的构造器是:FileWriter(file,true);则不会对原有文件进行覆盖,而是在后面追加内容

 @Test
 //最好使用try-catch-finally
    public void testFilWrites() throws IOException {
        //1.提供File类的对象,指明写出到的文件
        File file = new File("hello1.txt");

        //2.提供FileWriter的对象,用于数据的写出
        FileWriter fileWriter = new FileWriter(file,true);

        //3.写出的操作
        fileWriter.write("I have a dream!\n");
        fileWriter.write("you need to have a dream!\n");


        //4.资源关闭
        fileWriter.close();
    }
4. 对文件进行读写操作
@Test
    public void testFileReaderFileWriter(){
        FileReader fs = null;
        FileWriter fw = null;
        try {
            //1.创建File类的对象,指明读入和写出的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello2.txt");

            //不能使用字符流来处理图片等字节数据
//            File srcFile = new File("hello.jpg");
//            File destFile = new File("hello2.jpg");

            //2.创建输入流和输出流的对象
            fs = new FileReader(srcFile);
            fw = new FileWriter(destFile);

            //3.数据的读入和写出的操作
            char[] cbuf = new char[5];
            int len;//记录每次读入带cbuf数组中的字符个数
            while ((len = fs.read(cbuf)) != -1){
                //每次写出len个字符
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭流资源
            try {
                if (fw!=null){
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (fs!=null){
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

5.测试FileInputStream和FileOutPutStream的使用

结论:
1.对于文本文件(.txt,.java,.c),使用字符流处理
2.对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理

  @Test
    public void test() {
        FileInputStream stream = null;
        try {
            //1.File类的实例化,如果现在里面包含中文,就会乱码
            File file = new File("hello.txt");

            //2.流的实例化
            stream = new FileInputStream(file);
            //读数据
            byte[] bytes = new byte[5];
            int len;//记录每次读取的字节数
            while ((len = stream.read(bytes)) != -1){
                String s = new String(bytes, 0, len);
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stream!=null){
                //4.关闭资源
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
6. 实现对图片的复制
  @Test
    public void test1() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //1.File类的实例化
            File srcFile = new File("IO流的分类.png");
            File destFile = new File("IO流的分类1.png");

            //2.流的实例化
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //3.复制过程
            byte[] bytes = new byte[5];
            int len;
            while ((len = fis.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            try {
               if (fos != null){
                   fos.close();
               }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
               if (fis!=null){
                   fis.close();
               }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
7.实现指定路径文件的复制

1.先写一个方法

 public void copyFile(String srcPath,String destPath ){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //1.File类的实例化
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);

            //2.流的实例化
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //3.复制过程
            byte[] bytes = new byte[5];
            int len;
            while ((len = fis.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            try {
                if (fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis!=null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

2.再用单元测试方法对其进行测试

    @Test
    public void copyInputOutPutTest(){
        long start = System.currentTimeMillis();

        //String srcPath = "放入盘符下真实的(.jpg,.mp3,.mp4,.avi,.doc,.ppt,....)等文件";
        //String destPath = "不存在的(.jpg,.mp3,.mp4,.avi,.doc,.ppt,....)文件,会自动创建文件";

        //可以进行字符文件的复制,直接写出没有问题,但是在控制台看的话,可能会乱码
        String srcPath = "hello.txt";
        String destPath = "hello5.txt";


        copyFile(srcPath,destPath);

        long end =  System.currentTimeMillis();

        System.out.println("复制花费的时间为" + (end - start));//9毫秒
    }
处理流之一:缓冲流的使用

1.缓冲流
BufferedInputStream
BufferedOutPutStream
BufferedReader
BufferedWriter

2.作用:提供流的读取、写入的速度
提供读写速度的原因:内部提供了一个缓冲区,默认情况下是8kb

3.处理流:就是套接在已有流的基础上.
在这里插入图片描述

4. 实现非文本文件的复制

    @Test
    public void BufferedStreamTest() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.实例化file类的对象,指明要操作的文件
            File srcfile = new File("IO流的分类.png");
            File destFile = new File("IO流的分类2.png");

            //2.流的实例化
            //2.1节点流
            FileInputStream fis = new FileInputStream(srcfile);
            FileOutputStream fos = new FileOutputStream(destFile);

            //2.2缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3.复制的过程:读取,写入
            byte[] bytes = new byte[10];
            int len;
            while ((len  = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //4.资源关闭
        //要求:先关闭外层的流,在关闭内层的流

        //说明:关闭外层流时,内层流也自动进行关闭,关于内层流的关闭,可以省略。
//        fos.close();
//        fis.close();

    }
5.实现文件的复制方法
public void copyBuffered(String srcPath,String destPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            File srcfile = new File(srcPath);
            File destFile = new File(destPath);

            //2.流的实例化
            //2.1节点流
            FileInputStream fis = new FileInputStream(srcfile);
            FileOutputStream fos = new FileOutputStream(destFile);

            //2.2缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3.复制的过程:读取,写入
            byte[] bytes = new byte[10];
            int len;
            while ((len  = bis.read(bytes)) != -1){

                bos.write(bytes,0,len);

                bos.flush();//刷新缓冲区

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
6.对五中的方法进行测试
long start = System.currentTimeMillis();

        //String srcPath = "放入盘符下真实的(.jpg,.mp3,.mp4,.avi,.doc,.ppt,....)等文件";
        //String destPath = "不存在的(.jpg,.mp3,.mp4,.avi,.doc,.ppt,....)文件,会自动创建文件";

        //可以进行字符文件的复制,直接写出没有问题,但是在控制台看的话,可能会乱码
        //这里建议使用视频来复制,可以更清晰的看到差距
        String srcPath = "hello.txt";//内容使用的时出师表进行
        String destPath = "hello4.txt";


        copyBuffered(srcPath,destPath);

        long end =  System.currentTimeMillis();
	//提供了读写的速度
        System.out.println("复制花费的时间为" + (end - start));//0毫秒,与文件流的差距
7.使用BufferedReader和BufferedWriter实现文本的复制
 @Test
    public void testBufferedReaderBufferedWriter() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //创建文件和流
            br = new BufferedReader(new FileReader(new File("hello.txt")));
            bw = new BufferedWriter(new FileWriter(new File("hello6.txt")));

            //读写操作
            //方式一:使用char[]数组
//            char[] cbuf = new char[1024];
//            int len;
//            while ((len = br.read(cbuf)) != -1){
//                bw.write(cbuf,0,len);
//    //            bw.flush();
//            }
            //方式二:使用String
            String data;
            while ((data = br.readLine()) != null){
                bw.write(data + "\n");//data中不包含换行符,自行换行
//                newLine提供换行的操作
            }

        } 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.转换流(字符流)
InputStreamReader:将一个字节的输入流转换为字符的输入流
OutputStreamWrite:将一个字符的输出流转换为字节的输出流
2.作用:提供字节流与字符流之间的转换

3.解码:字节—>字符
编码:字符–>字节

4.字符集
常见的编码字符集有:
Unicode:国际标准码,它包含了几乎世界上所有的已经发现且需要使用的字符(如中文、日文、英文、德文等)。

ASCII:标准信息交换码

GB2312:中文字符集,包含ASCII字符集。ASCII部分用单字节表示,剩余部分用双字节表示。

GBK:GB2312的扩展,完整包含了GB2312的所有内容。

ISO8859-1:拉丁码表,欧洲码表

UTF-8;变长的编码格式,可以1-4个字节来表示

字符编码(character encoding),是编码字符集的字符和实际的存储值之间的转换关系。

常见的编码方式有:UTF-8(Unicode字符集的编码方式)、UTF-16(Unicode字符集的编码方式)、 UTF-32(Unicode字符集的编码方式)、ASCII(ASCII字符集的编码方式)等。
在这里插入图片描述

5. InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
   InputStreamReader isr = null;//使用系统默认的字符集
       try {
           //1.流的实例化
           FileInputStream fis = new FileInputStream("hello.txt");
//        InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
           //参数二指定了字符集,具体使用那个字符集,取决于hello.txt保存时的字符集
           isr = new InputStreamReader(fis,"UTF-8");

           //2.过程
           char[] chars =new char[20];
           int len;
           while ((len = isr.read(chars))!= -1){
               String str = new String(chars,0,len);
               System.out.println(str);
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           if(isr!=null){
               try {
                   isr.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
6.使用InputStreamReader和OutputStreamWriter
        InputStreamReader isr = null;
       OutputStreamWriter osw = null;
       try {
           //1.实例化file类的对象,指明要操作的文件
           File file1 = new File("hello.txt");//使用utf-8保存的文件
           File file2 = new File("hello_jbk.txt");

           //2.流的实例化
           FileInputStream fis = new FileInputStream(file1);
           FileOutputStream fos = new FileOutputStream(file2);

           isr = new InputStreamReader(fis,"utf-8");
           osw = new OutputStreamWriter(fos,"gbk");

           //3.实现过程(读写过程)
           char[] chars = new char[20];
           int len;
           while ((len = isr.read(chars)) != -1){
               osw.write(chars,0,len);
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally { //4.关闭资源

           if (isr!=null){
               //4.关闭资源
               try {
                   isr.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (osw!=null){
               //4.关闭资源
               try {
                   osw.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
   }

处理流之三:标准的输入输出流

System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出

System类的setIn(InputStream is) /setOut(PrintStream ps)方式重新指定输入和输出的流
在这里插入图片描述

从键盘输入字符串,要求将读取到的整行字符串转换成大写输出,然后继续进行输入操作, 直到输入”e“或者"exit"时,退出程序。

实现方式

1.Scanner实现,调用next()返回一个字符串
2.使用System.in实现System.in ----> 转换流---->BufferedReader的readLine()方法

  public static void main(String[] args) {
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            //1.流的实例化
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
            while (true){
                System.out.println("请输入字符串!");
                String data = br.readLine();
                if (data.equalsIgnoreCase("e") || data.equalsIgnoreCase("exit")){
                    System.out.println("程序结束");
                    break;
                }
                String s = data.toUpperCase();
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

处理流之四:打印流

PrintStream 和 PrintWriter

实现将基本数据类型的数据格式转化为字符串输出

提供了一系列重载的print()和println()
在这里插入图片描述

将从控制台输出的数据保存到磁盘中
  @Test
        public void test(){
            PrintStream ps = null;
            try {
                FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\test.txt"));
                //打印输出流,设置为自动刷新模式
                ps = new PrintStream(fos,true);
                if (ps != null){//把标准的输出流(控制台输出)改成文件
                    System.setOut(ps);
                }

                for (int i=0;i<=255;i++){//输出ASCII字符
                    System.out.println((char) i);
                    if (i % 50 == 0){//每50个数据一行
                        System.out.println();//换行
                    }
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (ps!=null){
                    ps.close();
                }
            }

        }
处理流之五: 数据流

DataInputStream 和 DataOutputStream

作用:用于读取和写入基本数据类型的变量或者字符串
在这里插入图片描述

将内存中的字符串、基本数据类型的变量写出到文件中。

处理异常:最好使用try-catch-finally ,如果不使用DataInputStream来查看的话,就会乱码

  @Test
        public void  test1() throws IOException {
            DataOutputStream dos =new DataOutputStream(new FileOutputStream("data.txt"));

            dos.writeUTF("六六六");
            dos.flush();//刷新操作,将内存中的数据写入文件中
            dos.writeInt(123);
            dos.flush();
            dos.writeBoolean(true);
            dos.flush();

            dos.close();
        }
将文件中的存储的基本数据类型和字符串读取到内存中,保存到变量中

注意:读取不同的数据类型的数据要与当前写入文件时,保存的数据的顺序一致。

 @Test
        public void  test2() throws IOException {
            DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
            //注意顺序问题
            String name = dis.readUTF();
            int age = dis.readInt();
            boolean isMale = dis.readBoolean();

            System.out.println("isMale=" + isMale );
            System.out.println("age=" + age );
            System.out.println("name=" + name );
            dis.close();
        }

处理流之六:对象流的使用

1.ObjectInputStream 和 ObjectOutputStream
2.作用:
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把java中的数据写入到数据源中,
也可以把对象从数据源中还原回来

序列化:用ObjectOutputStream类保存基本类型数据或对象机制
反序列化:用ObjectInputStream类读取基本类型数据或对象机制

对象的序列化机制:
允许把内存中的java对象转换为于平台无关的二进制流,从而允许把这种二进制流持久的保存在磁盘上,或者通过网络
将这种二进制流传输到另一个网络节点。当其他程序获取到了这种二进制流,就可以恢复成原来的java对象。

3.要想一个java对象是可以序列化的,需要满足相应的要求,详情可见person
在这里插入图片描述

自定义类实现实例化和反序列化的操作

person需要满足如下要求,方可序列化
为了让某个类是可以序列化的该类必须实现如下接口

Serializable否则就会抛出异常,该接口为标识接口,表示为可以序列化的
1.实现接口:Serializable

2.提供当前类的一个全局常量 :serialVersionUID(唯一标识, 常量值,可以任意取),如果没有这个常量,那么在进行进行修改操作的时候,就会出现异常,找不到该类

3.处理当前类需要实现接口(Serializable)外,还必须要保证其内部的所以属性,都是可以序列化的。

默认情况下,基本数据类型都是可以实例化的,但是使用其他类的对象时,就要实现Serializable接口,提供常量(serialVersionUID)

4.ObjectInputStream 和 ObjectOutputStream不能序列化static和transient修饰的成员变量

序列化只能对堆中的对象进行序列化不能对“方法区”中的对象进行序列化。
不希望序列化的属性,可以添加transient关键字;

示例:

public class Person implements Serializable {
    public static final long serialVersionUID = 42158184848448L;
    private String  name;
    private int age;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }
}

对象流的序列化过程:将内存中的java对象保存到磁盘中或者通过网络传输出去

在这里插入图片描述

  //1.流的实例化
        ObjectOutputStream oos = null;
        try {
            //该文件不是用于观看的,所以打开也是乱码的,需要进行反序列化过程
            oos = new ObjectOutputStream(new FileOutputStream("object.txt"));

            //2.操作过程
            oos.writeObject(new String("序列化过程"));
            oos.flush();//刷新操作

            //对对象进行操作
            //出现异常 java.io.NotSerializableException: com.java.Person
            //要想一个java对象是可以序列化的,需要满足相应的要求,详情可见person
            oos.writeObject(new Person("六六六",18));
            oos.flush();//刷新操作

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos!=null){
                //3.关闭资源
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
对象流的反序列化:将磁盘文件中的对象还原为内存中的一个java对象
 ObjectInputStream ois = null;
        try {
            //1.
            ois = new ObjectInputStream(new FileInputStream("object.txt"));

            //2.
            Object obj = ois.readObject();
            String str = (String) obj;

            Person person = (Person) ois.readObject();

            System.out.println(person);
            System.out.println("反"+str);
            //Person{name='六六六', age=18}
            //反序列化过程
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois!=null){
                //3.
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
三、随机存取文件流(RandomAccessFile)的使用

1.RandomAccessFile直接继承于java.long.Object类,实现了DataInput和DataOutput接口

2.RandomAccessFil既可以作为输入流,又可以作为输出流。

3.如果RandomAccessFile作为输出流出现时,写出的文件不存在,则在执行过程中,自动创建
如果文件存在,则会对原有文件内容进行覆盖,默认从头覆盖。
在这里插入图片描述

注意:

创建RandomAccessFile类的实例需要指明一个mode参数,该参数指定的是RandomAccessFile的访问模式

r:以只读的方式打开
rw:打开以便读取和写入
rwd:打开以便读取和写入,同步文件内容的更新
rws:打开以便读取和写入,同步文件内容和元数据的更新

如果模式为r只读,则不会创建文件,会去读取一个已经存在的文件,若文件不存在,则会出现异常。

如果模式为rw读写:如果文件不存在则会创建文件,如果 存在则不会创建文件。

rwd会里面写入到磁盘中,如果写入数据时发生异常,rwd模式已被write的数据写入到了硬盘中,rw则全部丢失。

示例:

 RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            //1.创建流的对象
            raf1 = new RandomAccessFile(new File("IO流的分类.png"),"r");
            raf2 = new RandomAccessFile(new File("IO流的分类1.png"),"rw");

            //2.操作过程
            byte[] bytes = new byte[1024];
            int len;
            while ((len = raf1.read(bytes)) != -1){
                raf2.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.关闭资源
            if (raf1!=null){
                //3.关闭资源
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf2!=null){
                //3.关闭资源
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
输出流出现(覆盖)
  @Test
    public void test1() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("hello.txt","rw");

        raf.write("wxyz".getBytes());

        raf.close();
    }
对原有数据进行插入操作,但是如果后面有数据,任会对后面的数据进行覆盖
  @Test
    public void test2() throws IOException {

        RandomAccessFile raf = new RandomAccessFile("hello.txt","rw");

        raf.seek(3);//将指针调到下标为3的位置
        raf.write("wxyz".getBytes());

        raf.close();
    }
对原有数据进行插入操作
   RandomAccessFile raf = new RandomAccessFile("hello.txt","rw");

        raf.seek(4);//将指针调到下标为3的位置

        //保存指针4后面的所以数据到builder中
        StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
        byte[] bytes = new byte[20];
        int len;
        while ((len = raf.read(bytes)) !=  -1){
            builder.append(new String(bytes,0,len));
        }
        //调回指针,写入数据
        raf.seek(4);
        raf.write("xyz".getBytes());

        //将StringBuilder中的数据写入到文件中
        raf.write(builder.toString().getBytes());

        raf.close();
    }
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值