Java IO流

//************************************************IO流**************611****************************************************//
            什么是文件?
            文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文件,excel文件...都是文件。
                    它既可以保存一张图片,也可以保持视频,声音等等~

                文件:在程序中,以流的形式来操作的
                流:数据在数据源(文件)和程序(内存)之间经历的路径
                输入流: 数据从数据源(文件)到程序(内存)的路径
                输出流:数据从程序(内存)到数据源(文件)的路径

Java程序(内存) <-----输入流---- 文件(磁盘)
Java程序(内存) -----输出流----> 文件(磁盘)
//**************************************************************************************************************************//
//***************************************************************612********************************************************//
//**************************************************************************************************************************//
        创建文件对象相关构造器和方法
        相关方法:
                new File(String pathname)              根据路径构建一个File对象
                new File(File parent,String child)     根据父目录文件+子路径构建
                new File(String parent,String child)   根据父目录+子路径构建
                creatNewFile   创建新文件

//***********************

        * 演示创建文件 *

public class FileCreate {
        public static void main(String[] args) {

        }

        //方式1 new File(String pathname)
        @Test
        public void create01() {
                String filePath = "e:\\news1.txt";
                File file = new File(filePath);

                File file = new File("e:\\news1.txt");  //在内存中形成。还没写入硬盘   //简化

                try {
                        file.createNewFile();   //真正写入硬盘!!!核心~
                        System.out.println("文件创建成功");
                } catch (IOException e) {   // IOException 扩大异常的范围,最大异常捕获
                        e.printStackTrace();
                }

        }

        //方式2 new File(File parent,String child) //根据父目录文件+子路径构建
        //e:\\news2.txt
        @Test
        public  void create02() {
                File parentFile = new File("e:\\");
                String fileName = "news2.txt";
                //这里的file对象,在java程序中,只是一个对象 ~~~~
                //      只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
                File file = new File(parentFile, fileName);

                File file = new File(new File("e:\\"), "news2.txt");  //简化

                try {
                        file.createNewFile();
                        System.out.println("创建成功~");
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }

        //方式3 new File(String parent,String child) //根据父目录+子路径构建
        @Test
        public void create03() {
                //String parentPath = "e:/";  也行!!!
                String parentPath = "e:\\";
                String fileName = "news4.txt";
                File file = new File(parentPath, fileName);
                
                File file = new File("e:\\", "news4.txt");   //也行!!简化

                try {
                        file.createNewFile();
                        System.out.println("创建成功~");
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }

                                        细节:如果不存在这个路径(文件夹),那就会报错!!

}
//**************************************************************************************************************************//
//***************************************************************613********************************************************//
//**************************************************************************************************************************//
public class FileInformation {
        public static void main(String[] args) {

        }

        //获取文件的信息
        @Test
        public void info() {
                //先创建文件对象
                File file = new File("e:\\QQQ\\news1.txt");   // txt 内容:hello麦合学长

                //调用相应的方法,得到对应信息
                System.out.println("文件名字=" + file.getName());  //news1.txt
                System.out.println("文件绝对路径=" + file.getAbsolutePath());  //e:\QQQ\news1.txt
                System.out.println("文件父级目录=" + file.getParent());   // e:\QQQ
                System.out.println("文件大小(字节)=" + file.length());  //17  5+4*3=17  一个汉字:3个字节(UTF-8)
                System.out.println("文件是否存在=" + file.exists());//T
                System.out.println("是不是一个文件=" + file.isFile());//T
                System.out.println("是不是一个目录=" + file.isDirectory());//F

        }
}

//**************************************************************************************************************************//
//***************************************************************614********************************************************//
//**************************************************************************************************************************//
        目录的操作和文件删除:
             mkdir创建一级目录
             mkdirs创建多级目录
             delete删除空目录或文件

//*********
public class Directory_ {
        public static void main(String[] args) {

        }
//****************
        判断 d:\\news1.txt 是否存在,如果存在就删除

        @Test
        public void m1() {

                String filePath = "e:\\news1.txt";
                File file = new File(filePath);
                if (file.exists()) {
                        if (file.delete()) {
                                System.out.println(filePath + "删除成功");
                        } else {
                                System.out.println(filePath + "删除失败");
                        }
                } else {
                        System.out.println("该文件不存在...");
                }

        }

//*********************
        判断 D:\\demo02 是否存在,存在就删除,否则提示不存在
        这里我们需要体会到,在java编程中,目录也被当做文件

        @Test
        public void m2() {

                String filePath = "D:\\demo02";
                File file = new File(filePath);
                if (file.exists()) {
                        if (file.delete()) {
                                System.out.println(filePath + "删除成功");
                        } else {
                                System.out.println(filePath + "删除失败");
                        }
                } else {
                        System.out.println("该目录不存在...");
                }

        }

        细节补充:这个文件(路径)必须是空的!!空的,才可以删除。不是空的话,删除失败~

        //判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
        @Test
        public void m3() {

                String directoryPath = "D:\\demo\\a\\b\\c";
                File file = new File(directoryPath);
                if (file.exists()) {
                        System.out.println(directoryPath + "存在..");
                } else {
                        if (file.mkdirs()) {  //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()
                                System.out.println(directoryPath + "创建成功..");
                        } else {
                                System.out.println(directoryPath + "创建失败...");
                        }
                }

                细节:"D:\\demo" 创建一级目录的话,可以。
                        加入:你本来就有"D:\\demo" ,想在里面再创建"a",那么"D:\\demo\\a" 也属于创建一级目录!!!变通一点~

        }
}
//**************************************************************************************************************************//
//****************************************************************615*******************************************************//
//**************************************************************************************************************************//
                                IO流原理及流的分类
        Java IO流原理:
        1.I/O是Input/Output的缩写l/O技术是非常实用的技术,用于处理数据传输如读/写文件,网络通讯等
        2.Java程序中,对于数据的输入/输出操作以”流(stream)” 的方式进行
        3.java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
        4.输入input: 读取外部数据(磁盘、光盘等存储设备的数据)到程序 (内存) 中
        5.输出output: 将程序(内存)数据输出到磁盘、光盘等存储设备中

                                流的分类
        按操作数据单位不同分为: 字节流(8 bit):二进制文件,音频,视频文件----> 无损操作     字符流(按字符):文本文件----> 效率高
        按数据流的流向不同分为: 输入流,输出流
        按流的角色的不同分为: 节点流,处理流/包装流

         细节:下面四个都是抽象类

     (抽象基类)             字节流               字符流
      输入流            InputStream            Reader
      输出流            OutputStream           Writer
       1) Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的
       2)由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

        流 VS 文件
用户 <----快递员(流)-----> 物品(文件)   如果是字节流:输出的时候,一次一趟    如果是字符流:输出的时候,一 flush/close一趟。

//**************************************************************************************************************************//
//*******************************************************************616****************************************************//
//**************************************************************************************************************************//
                                                InputStream:字节输入流
        InputStream抽象类,是所有类字节输入流的超类
        InputStream 常用的子类:
                1. FilelnputStream: 文件输入流
                2. BufferedInputStream: 缓冲字节输入流
                3. ObjectlnputStream: 对象字节输入流

                                   FileInputStream————————>InputStream
                                   ObjectInputStream————————>InputStream
        BufferedInputStream————————>FilterInputStream————————>InputStream

//***************

        * 演示FileInputStream的使用(字节输入流 文件--> 程序)
        */
public class FileInputStream_ {
        public static void main(String[] args) {

        }

        /**
         * 演示读取文件...
         * 单个字节的读取,效率比较低
         * -> 使用 read(byte[] b)
         */
        @Test
        public void readFile01() {
                String filePath = "e:\\hello.txt";
                int readData = 0;
                FileInputStream fileInputStream = null;  //扩大作用域。让 fileInputStream.close() 能捕获到
                try {
                        //创建 FileInputStream 对象,用于读取 文件
                        fileInputStream = new FileInputStream(filePath);
                        //从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。
                        //如果返回-1 , 表示读取完毕
                        while ((readData = fileInputStream.read()) != -1) {
                                System.out.print((char)readData);//转成char显示
                        }

                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        //关闭文件流,释放资源.
                        try {
                                fileInputStream.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }

        }

        细节补充:中文字,能不能单个字节流输出,行不行?
                不行!因为一个汉字=3个字节。加入一个汉字:1010...1011...1010....(24位) ---> 十进制abc
                        abc=c+b*16+a*16*16   可以验证一下,发现存在误差!!所以不行。


        /**
         * 使用 read(byte[] b) 读取文件,提高效率
         */
        @Test
        public void readFile02() {
                String filePath = "e:\\hello.txt";
                //字节数组
                byte[] buf = new byte[8]; //一次读取8个字节.
                int readLen = 0;
                FileInputStream fileInputStream = null;
                try {
                        //创建 FileInputStream 对象,用于读取 文件
                        fileInputStream = new FileInputStream(filePath);
                        //从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
                        //如果返回-1 , 表示读取完毕
                        //如果读取正常, 返回实际读取的字节数
                        while ((readLen = fileInputStream.read(buf)) != -1) {
                                System.out.print(new String(buf, 0, readLen));//显示
                        }

                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        //关闭文件流,释放资源.
                        try {
                                fileInputStream.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }

        }
}

        细节补充:1.
                  byte[] buf = {97,97,98,99,100};
                  System.out.println(new String(buf)); // aabcd

                2. 关于 new String(buf) 存储不确定性
                        目标文件:aaaaaaaabb   用 new byte[8] 存储:
                                第一次: aaaaaaaa
                                第二次: bbaaaaaa  而不是你们想的:bb
                                        也就是说,这是一个通道:不停地塞进去。塞满了,输进去。下一个数据用从头开始放
                                        但是,不会清空后面的内容!!! 所以,最后一组输进去的时候,如果没有存满很有可能多输进去上一次遗留的数据。
                3.所以,更多时候,我们用 new String(buf, 0, readLen) 来控制每次输进去的长度~

                4.输进去:aaaaaaaa bb
第一次:输进去 aaaaaaaa  new String(buf, 0, 8)   readLen= 8 = fileInputStream.read(buf)
第二次:输进去 bb  new String(buf, 0, 2)   readLen= 2 = fileInputStream.read(buf)
第二次:输进去 bbaaaaaa  new String(buf)

                5.我看弹幕说:new String(buf,0,readline) 可以解决中文问题,我试了一下,确实可以
目标文件:a麦合木提江    输出结果:a麦合�
                              ��提江   为什么会这么输出? 因为,一个汉字占3个字节。String 发现汉字时,占三个位置。
                                        但是,如果只剩两个/一个位置时,比如这个例子里“木”,只能输出乱码。输出一个字节
                                                下次,把剩下的两个字节输出。然后有足够位置,正常输出
                                        总之:一个数组,有三个位置,输出中文字。不够位置,乱码
//**************************************************************************************************************************//
//****************************************       细节补充                    ******************************************//
//**************************************************************************************************************************//

        @Test
        public void readFile02() {
                String filePath = "e:\\a.txt";
                //字节数组
                byte[] buf = new byte[4]; //    目标文件:我是
                                                         真
                                                         好人类
                int readLen = 0;
                FileInputStream fileInputStream = null;
                FileOutputStream fileOutputStream = null;
                try {
                        fileInputStream = new FileInputStream(filePath);
                        while ((readLen = fileInputStream.read(buf)) != -1) {
                                System.out.print(new String(buf, 0, readLen));//显示
                        }
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        //关闭文件流,释放资源.
                        try {
                                fileInputStream.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }
                        输出结果:我���
                                真
                                好人���

        请问:这个结果怎么来的?   哈哈哈哈哈 底层是怎么算的呢?有没有想过这个问题?  数组大小:4
                来推算一下吧。  麦合---->  麦(111) 合(122) 后面是:" ","\r"。但是,这两个算在下一行!
所以总的来说这样的:我(111),是(122)
            (22),真(333)
            (34),好(444),人(555),类(566)    如果汉字上,三个字节都是同一个,那就正常输出
                                                (因为,如果是相同的数字,说明这个汉字来自同一个数组)
                所以,上面的例子:“我”,“真”,“好”,“人” 来自同一个数组,可以正常输出!其他的,只能乱码~
                        输出结果:我(111)�(1)�(2)�(2)
                            (22)真(333)                        " ","\r"不会输出!!
                            (34)好(444),人(555),�(5),�(6),�(6)   懂了吗?再看一道题。

这道题改成:数组大小为3:
        所以总的来说这样的:我(111),是(222)
                    (33),真(344)
                    (45),好(556)人(667)类(778)    如果汉字上,三个字节都是同一个,那就正常输出


        所以,上面的例子:“我”,“是” 来自同一个数组,可以正常输出!其他的,只能乱码~
        输出结果:我(111),是(222)
            (33),�(3),�(4),�(4)                       " ","\r"不会输出!!
            (45),�(5),�(5),�(6),�(6),�(6),�(7),�(7),�(7),�(8)  但是,这么做发现不行!!和输出结果对不上。我很纳闷~~不应该呀?
                        想了半天,不知道哪里出了问题。先留着吧~~等以后再看看~~

        输出结果:麦合
        ���
        ������

//**************************************************************************************************************************//
//*******************************************************************617****************************************************//
//**************************************************************************************************************************//
public class FileOutputStream01 {
        public static void main(String[] args) {

        }

        /**
         * 演示使用FileOutputStream 将数据写到文件中,
         * 如果该文件不存在,则创建该文件
         */
        @Test
        public void writeFile() {

                //创建 FileOutputStream对象
                String filePath = "e:\\a.txt";
                FileOutputStream fileOutputStream = null;
                try {
                        //得到 FileOutputStream对象 对象
                        //老师说明
                        //1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
                        //2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
                        fileOutputStream = new FileOutputStream(filePath, true);
                        //写入一个字节
                        //fileOutputStream.write('H');//
                        //写入字符串
                        String str = "hsp,world!";
                        //str.getBytes() 可以把 字符串-> 字节数组
                        //fileOutputStream.write(str.getBytes());

                        // write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流
                             // str.getBytes() 是 byte[]    str.getBytes(),2,3----> 从第二个位置开始,取3个字符
                        fileOutputStream.write(str.getBytes(), 0, 3);

                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        try {
                                fileOutputStream.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }
}

                细节:
                      1.
                           String str = "abcd,ghf";
 这时String类型,在这儿不行   System.out.println(Arrays.toString(str.toCharArray())); //[a, b, c, d, ,, g, h, f]
 这时String类型,在这儿不行   System.out.println(Arrays.toString(str.getBytes()));   // [97, 98, 99, 100, 44, 103, 104, 102]
                           System.out.println((str.getBytes()));    // [B@677327b6

                     2. 追加 or 覆盖 问题
                        一个流,可以分批次传递多种数据。比如:一会儿加 'a',一会儿加'b',一会儿加'c'。直到close/flush,流结束
                        如果是字节流,那么它会一次一趟。也就是:加'a',立刻加上!无论输入还是输出。不管你有没有close
                        如果是字符流,那么它会一个流一趟。也就是:加'a',不会立刻加上!而是放到缓冲区。加'b',也是放到缓冲区
                                        无论输入还是输出,都先放到缓冲区。等你close/flush了,再把缓冲区的所有内容强行输出/写入。

为什么呢?   简单解释就是,字符流,消耗的空间大!!!不方便像字节流一样一次一趟。只能结束的时候,一次性运过去。节省资源。
                但是,它消耗的空间大!!因为内容都先存储在缓冲空间。

                覆盖还是追加?相当于一个流结束(close/flush)之后,下一个流堆上一个流,覆盖?还是追加。
                        同一个流,肯定都是追加~~这肯定的。

不带 true 时:1.不论创建文件字节输出流前磁盘上是否有该文件,最终都会通过当前字节文件输出流在磁盘上创建文件 2.覆盖的不是内容,而是直接替换文件

//**************************************************************************************************************************//
//********************************************************************618**************************************************//
//**************************************************************************************************************************//
public class FileCopy {
        public static void main(String[] args) {
                //完成 文件拷贝,将 e:\\Koala.jpg 拷贝 c:\\
                //思路分析
                //1. 创建文件的输入流 , 将文件读入到程序
                //2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件.
                String srcFilePath = "e:\\Koala.jpg";
                String destFilePath = "e:\\Koala3.jpg";
                FileInputStream fileInputStream = null;
                FileOutputStream fileOutputStream = null;

                try {

                        fileInputStream = new FileInputStream(srcFilePath);
                        fileOutputStream = new FileOutputStream(destFilePath);
                        //定义一个字节数组,提高读取效果
                        byte[] buf = new byte[1024];  //一个字节=8位   1KB=1024Byte(字节) 数组大小一般是1024的倍数
                        int readLen = 0;
                        while ((readLen = fileInputStream.read(buf)) != -1) {
                                //读取到后,就写入到文件 通过 fileOutputStream
                                //即,是一边读,一边写
                                fileOutputStream.write(buf, 0, readLen);//一定要使用这个方法
                                             //这里的 buf 在不断的更新~~
                        }
                        System.out.println("拷贝ok~");


                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        try {
                                //关闭输入流和输出流,释放资源
                                if (fileInputStream != null) {    //不等于 null ,才关闭。如果==null,就不用关闭
                                        fileInputStream.close();
                                }
                                if (fileOutputStream != null) {
                                        fileOutputStream.close();
                                }
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }


        }
}
//**************************************************************************************************************************//
//*****************************************************   细节补充    关于:边读边写   ******************************************//
//**************************************************************************************************************************//
public class FileCopy {
        public static void main(String[] args) {

                String srcFilePath = "e:\\a.txt";    //文件里面有中文
                String destFilePath = "e:\\Koala3.txt";
                FileInputStream fileInputStream = null;
                FileOutputStream fileOutputStream = null;
                int readData = 0;

                try {

                        fileInputStream = new FileInputStream(srcFilePath);
                        fileOutputStream = new FileOutputStream(destFilePath);
                        while ((readData = fileInputStream.read()) != -1) {
                                fileOutputStream.write(readData);
                        }
                        System.out.println("拷贝ok~");


                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        try {
                                //关闭输入流和输出流,释放资源
                                if (fileInputStream != null) {    //不等于 null ,才关闭。如果==null,就不用关闭
                                        fileInputStream.close();
                                }
                                if (fileOutputStream != null) {
                                        fileOutputStream.close();
                                }
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }
}

        看一下这个程序:我没有利用数组,而是单个单个的边读边写,进行单个字节流的拷贝
                字节流处理中文,单个字节处理的话,按理来说,应该不行!会出现乱码。
                因为,一个汉字是由三个字节构成的。你刚读汉字的第一个字节,直接写出来,肯定是乱码!
                但是,你运行这个程序发现,没有输出乱码。为啥呢?
                        很简单。Java设计者处理字节流的边读边写,还是跟字符流一样,边读,先把所有数据缓冲起来,最后一步再写!!
                如果,真的是边读边写,肯定会出现乱码。懂了吗?
                所以,老师说的“边读边写”,只是表面上看起来边读边写。但是,底层是最后再写!
                        我还考虑:是不是边读的时候,如果遇到换行符,会不会写出来?
                                并没有!!!哪怕换行符,也会存在缓冲区里面。
                                        按理来说,换行时写出来,应该也可以。不会有乱码~但是,没有这么设计~我也不晓得
                所以,字节流的拷贝,在底层做了优化~~

                你还可以这么想:设计者为啥这么设计?如果你想拷贝中文的话,用数组不就行了?不用中文,就用单个字节拷贝。
                        你再仔细一想,也不行!!!我给你举个例子:
                                比如:你想拷贝 “麦合学长” 3+3+3+3=12
                                如果你用大小为2的数组进行拷贝:读了“麦”的前两个字节,就立刻写出来,肯定是乱码!
                        这时,你可能抬杠说:你把数组大小设置成3不就行了?刚好能输出。
                                那你想拷贝:“麦合a学长”,阁下怎么通过字节流拷贝呢?
                                        无论你怎么设计数组大小,都不可能边读边写这个字符串!!!所以,只能设计成:先读,最后再写出来!!
//**************************************************************************************************************************//
//*********************************************************************619*************************************************//
//**************************************************************************************************************************//
                FileReader 和 FileWriter 介绍
        FileReader————————> InputStreamReader————————> Reader
        FileWriter————————> OutputStreamWriter————————> Writer

        FileReader 和 FileWriter 是字符流,即按照字符来操作io
        FileReader相关方法:
                1) new FileReader(File/String)
                2)read:每次读取单个字符,返回该字符,如果到文件未尾返回-1
                3) read(char[]): 批量读取多个字符到数组,返回读取到的字符数如果到文件未尾返回-1
        相关API:
                1)new String(char[]):将charll转换成String
                2) new String(char[],off,len):将char[]的指定部分转换成String

        FileWriter常用方法
                1)new FileWriter(File/String): 覆盖模式,相当于流的指针在首端
                2) new FileWriter(File/String,true): 追加模式,相当于流的指针在尾端
                3) write(int):写入单个字符
                4)write(char[]):写入指定数组
                5)write(char[],off,len):写入指定数组的指定部分
                6) write (string) : 写入整个字符串
                7)write(string,off,len):写入字符串的指定部分
                相关API:
                        String类: toCharArray:将String转换成charll
                >注意:
                        FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件!!     close = flush+关闭 (核心是 flush)
//**************************************************************************************************************************//
//*********************************************************************620*************************************************//
//**************************************************************************************************************************//
public class FileReader_ {
        public static void main(String[] args) {


        }

        /**
         * 单个字符读取文件
         */
        @Test
        public void readFile01() {
                String filePath = "e:\\story.txt";
                FileReader fileReader = null;
                int data = 0;
                //1. 创建FileReader对象
                try {
                        fileReader = new FileReader(filePath);
                        //循环读取 使用read, 单个字符读取
                        while ((data = fileReader.read()) != -1) {  // data 平时输出字符,但是,最后结束了输出 -1
                                System.out.print((char) data);   // 因为你定义的时候是 int data ,所以这里强转成 char
                        }

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

        /**
         * 字符数组读取文件
         */
        @Test
        public void readFile02() {
                System.out.println("~~~readFile02 ~~~");
                String filePath = "e:\\story.txt";
                FileReader fileReader = null;

                int readLen = 0;
                char[] buf = new char[8];
                //1. 创建FileReader对象
                try {
                        fileReader = new FileReader(filePath);
                        //循环读取 使用read(buf), 返回的是实际读取到的字符数
                        //如果返回-1, 说明到文件结束
                        while ((readLen = fileReader.read(buf)) != -1) {
                                System.out.print(new String(buf, 0, readLen));
                        }

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

}

        细节:
                FileReader 字符流读原则:按理来说:和前面说的一样,把所有字符串先存到缓冲区里面。等close的时候,才会把缓冲区的强行读出来。
                        还有一种:当遇到换行时,也会从缓冲区里面读出来。也就是说:缓冲区不存放换行符。最后一行,也会强行读出来,不用close也行。
                                        但是,写的时候,管你有没有换行,必须 close/flush 时才会写入 !!!

                可以李继承:JVM给底层做了优化。换行的时候,也给你读出来。但是,写的时候必须flush/close才给你写!!!

                当数组方式时候:换行的时:先存一个空格,再存 \r 。    同样,换行/close/flush 的时候,才会读!!不然,都存到缓冲区里。
//**************************************************************************************************************************//
//**********************************************************************621*************************************************//
//**************************************************************************************************************************//
public class FileWriter_ {
        public static void main(String[] args) {

                String filePath = "e:\\note.txt";
                //创建FileWriter对象
                FileWriter fileWriter = null;
                char[] chars = {'a', 'b', 'c'};
                try {
                        fileWriter = new FileWriter(filePath);//默认是覆盖写入
//            3) write(int):写入单个字符
                        fileWriter.write('H');
//            4) write(char[]):写入指定数组
                        fileWriter.write(chars);
//            5) write(char[],off,len):写入指定数组的指定部分
                        fileWriter.write("韩顺平教育".toCharArray(), 0, 3);
//            6) write(string):写入整个字符串
                        fileWriter.write(" 你好北京~");
                        fileWriter.write("风雨之后,定见彩虹");
//            7) write(string,off,len):写入字符串的指定部分
                        fileWriter.write("上海天津", 0, 2);
                        //在数据量大的情况下,可以使用循环操作.


                } catch (IOException e) {
                        e.printStackTrace();
                } finally {

                        //对应FileWriter , 一定要关闭流,或者flush才能真正的把数据写入到文件
                        //老韩看源码就知道原因.
            /*
                看看代码
                private void writeBytes() throws IOException {
        this.bb.flip();
        int var1 = this.bb.limit();
        int var2 = this.bb.position();

        assert var2 <= var1;

        int var3 = var2 <= var1 ? var1 - var2 : 0;
        if (var3 > 0) {
            if (this.ch != null) {
                assert this.ch.write(this.bb) == var3 : var3;
            } else {
                this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
            }
        }

        this.bb.clear();
    }
             */
                        try {
                                //fileWriter.flush();
                                //关闭文件流,等价 flush() + 关闭
                                fileWriter.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }

                }

                System.out.println("程序结束...");

        }
}

                细节:
                        String str = "abcd,ghf";
                        System.out.println(Arrays.toString(str.toCharArray()));   // [a, b, c, d, ,, g, h, f]

//**************************************************************************************************************************//
//*********************************************************************622**************************************************//
//**************************************************************************************************************************//
                        节点流和处理流
     基本介绍
         节点流:可以从一个特定的数据源(数组,字符串,管道)读写数据,如FileReader、FileWriter
          处理流(也叫包装流):“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也更加灵活,如BufferedReader、BufferedWriter
                例如:BufferedReader 类中,有属性Reader, 即可以封装一个节点流,该节点流可以是任意(数组,管道,字符串).只要是Reader子类

public class BufferedReader extends Reader {

        private Reader in;
        ........
        }

public class BufferedWriter extends Writer {

        private Writer out;
        ......
        }
//**************************************************************************************************************************//
//**********************************************************************623************************************************//
//**************************************************************************************************************************//

                                节点流和处理流
         节点流和处理流的区别和联系:
                1.节点流是底层流/低级流,直接跟数据源相接。
                2.处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。[源码理解]
                3.处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连[模拟修饰器设计模式]

        处理流的功能主要体现在以下两个方面
        1.性能的提高:主要以增加缓冲的方式来提高输入输出的效率
        2.操作的便捷: 处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便

//****************************

public class Test_ {
        public static void main(String[] args) {


                BufferedReader_ bufferedReader_ = new BufferedReader_(new FileReader_());
                bufferedReader_.readFiles(10);
                bufferedReader_.readFile();
                //Serializable
                //Externalizable
                //ObjectInputStream
                //ObjectOutputStream
                //这次希望通过 BufferedReader_ 多次读取字符串
                BufferedReader_ bufferedReader_2 = new BufferedReader_(new StringReader_());
                bufferedReader_2.readStrings(5);

                优化完之后,只需要用 read 方法,会自动绑定~~
        }
}
//**************************

 * 做成处理流/包装流

public class BufferedReader_ extends Reader_ {

        private Reader_ reader_; //属性是 Reader_类型

        //接收Reader_ 子类对象
        public BufferedReader_(Reader_ reader_) {
                this.reader_ = reader_;
        }

        public void readFile() { //封装一层
                reader_.readFile();
        }

        //让方法更加灵活, 多次读取文件, 或者加缓冲byte[] ....
        public void readFiles(int num) {
                for(int i = 0; i < num; i++) {
                        reader_.readFile();
                }
        }

        //扩展 readString, 批量处理字符串数据
        public void readStrings(int num) {
                for(int i = 0; i <num; i++) {
                        reader_.readString();
                }
        }

}
//***************************

public abstract class Reader_ { //抽象类
        public void readFile() {
        }
        public void readString() {
        }

        //在Reader_ 抽象类,使用read方法统一管理.
        //后面在调用时,利于对象动态绑定机制, 绑定到对应的实现子类即可.
        public abstract void read();   // 也可以直接写这一个  优化
}

//******************************

 * 节点流
         */
public class FileReader_ extends Reader_ {

        public void readFile() {
                System.out.println("对文件进行读取...");
        }
        public void read() {System.out.println("对文件进行读取...");}  // 也可以直接写   优化

}
//*****************

 * 节点流
         */
public class StringReader_ extends Reader_ {
        public void readString() {
                System.out.println("读取字符串..");
        }
        public void read() {System.out.println("读取字符串...");}  // 也可以直接写   优化

}



//**************************************************************************************************************************//
//************************************************************************624***********************************************//
//**************************************************************************************************************************//

                                          节点流和处理流
                1.处理流-BufferedReader和BufferedWriter 是按照“字符”来读取数据的属于字符流
                2.关闭时处理流,只需要关闭外层流即可
                          原因:当你关闭“处理流”的时候,底层会自动关闭“节点流”。所以我们说:关闭外层流
                    细节:处理流只是做了包装!! 真正处理信息的是,节点流~~~

                字符流:尽量用文本文件。不要用二进制文件:图片,视频,音频。不然,会有数据的损失!!!

//********************

        * 演示bufferedReader 使用 *

public class BufferedReader_ {
        public static void main(String[] args) throws Exception {

                String filePath = "e:\\a.java";
                //创建bufferedReader
                BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
                //读取
                String line; //按行读取, 效率高
                //说明
                //1. bufferedReader.readLine() 是按行读取文件
                //2. 当返回null 时,表示文件读取完毕
                while ((line = bufferedReader.readLine()) != null) {   // line 是内容 。 结束的时候是 null
                        System.out.println(line);
                }

                //关闭流, 这里注意,只需要关闭 BufferedReader ,因为底层会自动的去关闭 节点流
                //FileReader。
        /*
            public void close() throws IOException {
                synchronized (lock) {
                    if (in == null)
                        return;
                    try {
                        in.close();//  in 就是我们传入的 new FileReader(filePath), 关闭了.
                    } finally {
                        in = null;
                        cb = null;
                    }
                }
            }

         */
                bufferedReader.close();

        }
}

                细节补充:这个方式是按行输出。其实,在前面我说过,输出的时候,如果遇到换行符/close/flush都会输出。如果你指定数组,那么缓冲空间就是指定的数组。
                        如果按照现在的按行输出,那么缓冲空间就是行数(不会固定),更加高效的输出。
                        无论是单个/数组/按行----> 改变的是缓冲空间的大小。 但是都会默认:遇到换行符/close/flush都会输出(Read)
//**************************************************************************************************************************//
//*************************************************************************625**********************************************//
//**************************************************************************************************************************//
                        * 演示BufferedWriter的使用*

public class BufferedWriter_ {
        public static void main(String[] args) throws IOException {
                String filePath = "e:\\ok.txt";
                //创建BufferedWriter
                //说明:
                //1. new FileWriter(filePath, true) 表示以追加的方式写入
                //2. new FileWriter(filePath) , 表示以覆盖的方式写入
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
                bufferedWriter.write("hello, 韩顺平教育!");
                bufferedWriter.newLine();//插入一个和系统相关的换行
                bufferedWriter.write("hello2, 韩顺平教育!");
                bufferedWriter.newLine();
                bufferedWriter.write("hello3, 韩顺平教育!");
                bufferedWriter.newLine();

                //说明:关闭外层流即可 , 传入的 new FileWriter(filePath) ,会在底层关闭
                bufferedWriter.close();

        }
}
//**************************************************************************************************************************//
//*************************************************************************626**********************************************//
//**************************************************************************************************************************//
public class BufferedCopy_ {

        public static void main(String[] args) {


                //老韩说明
                //1. BufferedReader 和 BufferedWriter 是安装字符操作
                //2. 不要去操作 二进制文件[声音,视频,doc, pdf ], 可能造成文件损坏

                //BufferedInputStream
                //BufferedOutputStream

                String srcFilePath = "e:\\a.java";
                String destFilePath = "e:\\a2.java";

                String srcFilePath = "e:\\0245_韩顺平零基础学Java_引出this.avi";
                String destFilePath = "e:\\a2韩顺平.avi";   // 发现大小还变大了。拷贝有损~~不行!!

                BufferedReader br = null;
                BufferedWriter bw = null;
                String line;
                try {
                        br = new BufferedReader(new FileReader(srcFilePath));
                        bw = new BufferedWriter(new FileWriter(destFilePath));

                        //说明: readLine 读取一行内容,但是没有换行
                        while ((line = br.readLine()) != null) {
                                //每读取一行,就写入
                                bw.write(line);
                                //插入一个换行
                                bw.newLine();
                        }
                        System.out.println("拷贝完毕...");

                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        //关闭流
                        try {
                                if(br != null) {
                                        br.close();
                                }
                                if(bw != null) {
                                        bw.close();
                                }
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }


        }
}

                细节补充:写的话,没有对应的文件,会自动创建,但是没有目录的话,会报异常
//**************************************************************************************************************************//
//*************************************************************************627**********************************************//
//**************************************************************************************************************************//
                BufferedOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统

       BufferedOutputStream(OutPutStream) ————————> FilterOutputStream 属性:OutPutStream out;————————> OutputStream
       BufferedInputStream(OutPutStream) ————————> FilterInputStream 属性:InPutStream in;————————> InputStream

                                                                          FileInputStream————————>InputStream
                                                                          FileOutputStream————————>OutputStream
                        ObjectInputStream 属性:InputStream————————> InputStream

                        FileReader————————> InputStreamReader————————> Reader
                        FileWriter————————> OutputStreamWriter————————> Writer
//**************************************************************************************************************************//
//**************************************************************************628*********************************************//
//**************************************************************************************************************************//
                        * 演示使用BufferedOutputStream 和 BufferedInputStream使用完成二进制文件拷贝

                        * 思考:字节流可以操作二进制文件,可以操作文本文件吗?当然可以!!底层做了优化~~

public class BufferedCopy02 {
        public static void main(String[] args) {

                String srcFilePath = "e:\\Koala.jpg";
                String destFilePath = "e:\\hsp.jpg";  //完好无损的拷贝!! 用字符流,就不行!!

                String srcFilePath = "e:\\0245_韩顺平零基础学Java_引出this.avi";
                String destFilePath = "e:\\hsp.avi";  //完好无损的拷贝!! 用字符流,就不行!!

                String srcFilePath = "e:\\a.java";
                String destFilePath = "e:\\a3.java";   // 中文的话,单个字节输出,可以!!底层做了优化

                //创建BufferedOutputStream对象BufferedInputStream对象
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;

                try {
                        //因为 FileInputStream  是 InputStream 子类
                        bis = new BufferedInputStream(new FileInputStream(srcFilePath));
                        bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

                        //循环的读取文件,并写入到 destFilePath
                        byte[] buff = new byte[1024];
                        int readLen = 0;
                        //当返回 -1 时,就表示文件读取完毕
                        while ((readLen = bis.read(buff)) != -1) {
                                bos.write(buff, 0, readLen);
                        }

                        System.out.println("文件拷贝完毕~~~");

                } catch (IOException e) {
                        e.printStackTrace();
                } finally {

                        //关闭流 , 关闭外层的处理流即可,底层会去关闭节点流
                        try {
                                if(bis != null) {
                                        bis.close();
                                }
                                if(bos != null) {
                                        bos.close();
                                }
                        } catch (IOException e) {
                                e.printStackTrace();
                        }

                }


        }
}

                又又又一个细节:当你通过 FileInputStream FileOutputStream进行拷贝的时候,表面上是边读,边写。但是,底层上不会边读边写!!
                        底层上做了优化:如果字节流进行边读边写,先所有都读一遍,然后,最后进行写!
                                                前面非常详细的说过~~ (500行)
//**************************************************************************************************************************//
//****************************************************************************629*******************************************//
//**************************************************************************************************************************//
                                                节点流和处理流
              对象流-ObjectInputStream和ObjectOutputStream
                  看一个需求:
                        1.将int num = 100 这个 int 数据保存到文件中,注意不是 100 数字,而是 int 100,并且,能够从文件中直接恢复 int 100 (反序列化)
                        2.将 Dog dog = new Dog(“小黄”,3) 这个 dog对象 保存到 文件中,并且能够从文件恢复。
                                不能只保存(“小黄”,3)。应该把数据类型也保存。不然,不知道这个“小黄”是人名?狗名?
                                        dog 是 Dog 类   int:3   String:小黄
                        3.上面的要求,就是 能够将 “基本数据类型” 或者 “对象” 进行 序列化 和 反序列化操作

                        序列化和反序列化
                        1.序列化就是在保存数据时,保存数据的“值”和“数据类型”
                        2.反序列化就是在恢复数据时,恢复数据的“值”和“数据类型”
                        3.需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,
                                该类必须实现如下两个接口之一:
                                        Serializable // 这是一个标记接口,没有方法(比较推荐)   可序列化的
                                                        public interface Serializable{}  // 什么都没有!!
                                        Externalizable  //该接口需要方法一定实现,比较麻烦,所以不推荐!

                                                23
    1.功能: 提供了对基本类型或对象类型的序列化和反序列化的方法
    2.ObjectOutputStream 提供 序列化功能
    3.ObjectInputStream 提供 反序列化功能

                              需要序列化的类才需要实现Serializable,这个类是提供实现序列化的方法

          ObjectInputStream 属性:InputStream————————> InputStream (抽象类)
          ObjectOutputStream 属性:OutputStream————————> OutputStream (抽象类)

//**************************************************************************************************************************//
//****************************************************************************630*******************************************//
//**************************************************************************************************************************//
         * 演示ObjectOutputStream的使用, 完成数据的序列化 */

public class ObjectOutStream_ {
        public static void main(String[] args) throws Exception {
                //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
                String filePath = "e:\\data.dat";

                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));

                //序列化数据到 e:\data.dat
                oos.writeInt(100);// int -> Integer (实现了 Serializable)
                oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable)
                oos.writeChar('a');// char -> Character (实现了 Serializable)
                oos.writeDouble(9.5);// double -> Double (实现了 Serializable)
                oos.writeUTF("韩顺平教育");//String
                //保存一个dog对象
                oos.writeObject(new Dog("旺财", 10));
                oos.close();
                System.out.println("数据保存完毕(序列化形式)");


        }
}

  如果你想 反序列的时候, toString / 想调用 Dog 的方法(向下转型),那就在序列化和反序列化,必须引用同一个Dog 类。
                所以,必须把Dog设置成public方法。
                        如果反序列化的时候,不在同一个包,那就导入Dog的包!
//class Dog implements Serializable {   //这个不行!
//        final int age;
//        final String name;
//
//        public Dog(String name,int age ) {
//                this.age = age;
//                this.name = name;
//        }
//}

                细节:
                        FileOutputStream oos = new FileOutputStream(filePath);  //这时普通的输出字节流

                        oos.writeInt(100);  //不行!!!
                        oos.write(100);  //可以!!! 100 就是单纯的文本
                        如果你想输入,int 100 ,那就必须通过 ObjectOutputStream 来解决!

                        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
                        oos.writeInt(100);  //这样才对!!!

细节:如果格式是 dat ,会出现视频。不想老师那样文本。所以,我就只好改成 txt 格式。
显示:
         w    d a@#       闊╅『骞虫暀鑲瞫r Dogy欪Pl? I ageL namet Ljava/lang/String;xp
        t 鏃鸿储

你通过这些数据,你会发现:有 age ,name ,String 等信息。但是,你存的是:100 , true , a, "旺财", 10 .没有存储 age ,name ,String 等数据类型。
        所以,这就体现了序列化的本质:存储 值 + 数据类型 。更加完整的存储信息!!!

                                 反序列化顺序,必须和序列化顺序一样!!!!!

//**************************************************************************************************************************//
//****************************************************************************631*******************************************//
//**************************************************************************************************************************//

        import com.hspedu.outputstream_.Dog;    // 必须导入!!(如果反序列化和序列化,不在一个包的话)

/**
 * @author 韩顺平
 * @version 1.0
 */
public class ObjectInputStream_ {
        public static void main(String[] args) throws IOException, ClassNotFoundException {

                //指定反序列化的文件
                String filePath = "e:\\data.dat";

                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));

                //读取
                //老师解读
                //1. 读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
                //2. 否则会出现异常

                反序列化顺序,必须和序列化顺序一样!!!!!

                System.out.println(ois.readInt());
                System.out.println(ois.readBoolean());

                System.out.println(ois.readChar());
                System.out.println(ois.readDouble());
                System.out.println(ois.readUTF());


                //dog 的编译类型是 Object , dog 的运行类型是 Dog
                Object dog = ois.readObject();

                System.out.println("运行类型=" + dog.getClass());
                System.out.println("dog信息=" + dog);//底层 Object -> Dog

                //这里是特别重要的细节:

                //1. 如果我们希望调用Dog的方法, 需要向下转型   Object----> Dog
                //2. 需要我们将Dog类的定义,放在到可以引用的位置
                        import com.hspedu.outputstream_.Dog; // 你想向下转型,必须导入这个 Dog 类
                Dog dog2 = (Dog)dog;
                System.out.println(dog2.getName()); //旺财..

                //关闭流, 关闭外层流即可,底层会关闭 FileInputStream 流
                ois.close();

                细节:序列化 和 反序列化 ,引用的 Dog 必须是同一个!!  所以,把 Dog 类设置成 public 类!!!


        }
}

//************************
public class Dog implements Serializable {
        private String name;
        private int age;

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

        @Override
        public String toString() {
                return "Dog{" +
                        "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;
        }
}
//**************************************************************************************************************************//
//****************************************************************************632******************************************//
//**************************************************************************************************************************//

        注意事项和细节说明:
                1)读写顺序要一致
                2)要求序列化或反序列化对象,需要实现 Serializable
                3)序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
                4)序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
                5) 序列化对象时,要求里面属性的类型也需要实现序列化接口
                6)序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化
                        // Integer extends Number , Number implements Serializable ,所以 Integer 实现了Serializable


public class Dog implements Serializable {
        private String name;
        private int age;
        //序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
             // static transient 不会被序列化!!! color ,nation 都会输出:null
        private static String nation;
        private transient String color;

        //序列化对象时,要求里面属性的类型也需要实现序列化接口
        private Master master = new Master();  // 加入Master 没有序列化,会报错!!必须序列化。

//                                        public class Master implements Serializable {    写上!!
//                                        }


        private static final long serialVersionUID = 1L;
       // serialVersionUID 序列化的版本号,可以提高兼容性      比如加一些属性~~
                        // 也就是说:如果你再加一些属性,JVM在序列化和反序列化时,不会觉得那是新的类!!
        //                      会觉得那是原先Dog类的增强版/修改版
                //说得清楚一点就是:当你序列化之后,如果再修改,把这个写上,不用再序列化。直接反序列化就行~~

        public Dog(String name, int age, String nation, String color) {
                this.name = name;
                this.age = age;
                this.color = color;
                this.nation = nation;
        }

        @Override
        public String toString() {
                return "Dog{" +
                        "name='" + name + '\'' +
                        ", age=" + age +
                        ", color='" + color + '\'' +
                        '}' + nation + " " +master;
        }

        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;
        }
}
//**************************************************************************************************************************//
//****************************************************************************633*******************************************//
//**************************************************************************************************************************//
                                节点流和处理流
                标准输入输出流:
                com.hspedu.standard         InputAndOutput.java

                                               类型               默认设备
                System.in 标准输入          InputStream             键盘
                System.out 标准输出         PrintStream            显示器



public class InputAndOutput {
        public static void main(String[] args) {
                // System.in:  public final static InputStream in = null;
                // System.in 编译类型   InputStream
                // System.in 运行类型   BufferedInputStream
                // 表示的是标准输入 键盘
                System.out.println(System.in.getClass());

                //老韩解读
                // System.out: public final static PrintStream out = null;
                // 编译类型 PrintStream
                // 运行类型 PrintStream
                // 表示标准输出 显示器
                System.out.println(System.out.getClass());

                System.out.println("hello, 韩顺平教育~");

                Scanner scanner = new Scanner(System.in);
                System.out.println("输入内容");
                String next = scanner.next();
                System.out.println("next=" + next);


        }
}




//**************************************************************************************************************************//
//***************************************************************************634*******************************************//
//**************************************************************************************************************************//
        * 看一个中文乱码问题
        */
public class CodeQuestion {
        public static void main(String[] args) throws IOException {
                //读取e:\\a.txt 文件到程序
                //思路
                //1.  创建字符输入流 BufferedReader [处理流]
                //2. 使用 BufferedReader 对象读取a.txt
                //3. 默认情况下,读取文件是按照 utf-8 编码
                String filePath = "e:\\a.txt";
                BufferedReader br = new BufferedReader(new FileReader(filePath));

                String s = br.readLine();
                System.out.println("读取到的内容: " + s);
                br.close();
                
        }
}
        细节补充: hsphsp韩顺平  如果txt保存格式:utf-8 ,那么输出也是utf-8,那就正常输出
                              如果txt保存格式:ANSI ,那么输出是utf-8,那就乱码: hsphsp��˳ƽ
                   ANSI----> GBK

                         国际码中文是三个字节的,utf-8中文是两个字节的。所以会输出乱码~
 任何文件在底层保存字符时都是将所对应的二进制存储在一个一个字节中,转换流会维持一个缓冲,然后通过字节流将文件所有的字节读进来(无损),
                        再在转换流中指定编码方式,即以某种规则解读所读进来的所有字节
------> 所以本质:字节流--> 字符流
//**************************************************************************************************************************//
//*****************************************************************************635*******************************************//
//**************************************************************************************************************************//
                 节点流和处理流转换流-InputStreamReader 和 OutputStreamWriter

                 >介绍
                 1.InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成(转换)Reader(字符流)
                                 InputStreamReader:InputStream----> Reader
                 2.OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)
                                 OutputStreamWriter:OutputStream----> Writer
                 3.当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
                 4.可以在使用时指定编码格式(比如 utf-8,gbk,gb2312,ISO8859-1 等)

                OutputStreamWriter(OutputStream,Charset)   // Charset :格式
                InputStreamWriter(InputStream,Charset)   // Charset :格式
//**************************************************************************************************************************//
//******************************************************************************636*****************************************//
//**************************************************************************************************************************//
         * 演示使用 InputStreamReader 转换流解决中文乱码问题
         * 将字节流 FileInputStream 转成字符流  InputStreamReader, 指定编码 gbk/utf-8

public class InputStreamReader_ {
        public static void main(String[] args) throws IOException {

                String filePath = "e:\\a.txt";
                //解读
                //1. 把 FileInputStream 转成 InputStreamReader
                //2. 指定编码 gbk
                InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
                //3. 把 InputStreamReader 传入 BufferedReader
                                // 因为 BufferedReader 有些方法(按行读取等),效率高一些

                //这道题包装了三次! 通过 InputStreamReader 指定 "gbk"读取~利用 BufferedReader 快速读取!
                                // 核心:FileInputStream

                BufferedReader br = new BufferedReader(isr);

                //将2 和 3 合在一起
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));

                                // BufferedReader (Reader 的实现子类) , InputStreamReader(InputStream 的子类)
                //4. 读取
                String s = br.readLine();
                System.out.println("读取内容=" + s);   // 正常输出: hsphsp韩顺平 (ANSI----> GBK)
                //5. 关闭外层流
                br.close();

        }


}
//**************************************************************************************************************************//
//******************************************************************************637*****************************************//
//**************************************************************************************************************************//

        * 演示 OutputStreamWriter 使用
        * 把FileOutputStream 字节流,转成字符流 OutputStreamWriter
        * 指定处理的编码 gbk/utf-8/utf8

public class OutputStreamWriter_ {
        public static void main(String[] args) throws IOException {
                String filePath = "e:\\hsp.txt";
                String charSet = "utf-8";
                OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
                osw.write("hi, 韩顺平教育");
                osw.close();
                System.out.println("按照 " + charSet + " 保存文件成功~");


        }
}
//**************************************************************************************************************************//
//*******************************************************************************637***************************************//
//**************************************************************************************************************************//
                        * 演示PrintStream (字节打印流/输出流)*

public class PrintStream_ {
        public static void main(String[] args) throws IOException {

                PrintStream out = System.out;
                //在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
        /*
             public void print(String s) {
                if (s == null) {
                    s = "null";
                }
                write(s);
            }

         */
                out.print("john, hello");  // 默认输出在显示器上
                //因为print底层使用的是write , 所以我们可以直接调用write进行打印/输出
                out.write("韩顺平,你好".getBytes());  // 本质还是字节流,所以必须是 Butes
                out.close();

                //我们可以去修改打印流输出的位置/设备
                //1. 输出修改成到 "e:\\f1.txt"
                //2. "hello, 韩顺平教育~" 就会输出到 e:\f1.txt
                //3. public static void setOut(PrintStream out) {
                //        checkIO();
                //        setOut0(out); // native 方法,修改了out
                //   }

                System.setOut(new PrintStream("e:\\f1.txt"));
                System.out.println("hello, 韩顺平教育~");   // 会在"e:\\f1.txt" 上输出


        }
}

//**************************************************************************************************************************//
//********************************************************************************638****************************************//
//**************************************************************************************************************************//
                * 演示 PrintWriter 使用方式 *

public class PrintWriter_ {
        public static void main(String[] args) throws IOException {

                PrintWriter printWriter = new PrintWriter(System.out);   // System.out 标准输出:默认显示器

                PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
                printWriter.print("hi, 北京你好~~~~");
                printWriter.close();// flush + 关闭流, 才会将数据写入到文件.. (核心是:flush)

        }
}

        细节补充:当你 new FileWriter("e:\\f2.txt") 创建文件的时候,清空文件,重新写~
                如果你写了内容,没有关闭流,则不会输出
//**************************************************************************************************************************//
//********************************************************************************639***************************************//
//**************************************************************************************************************************//
                                                Properties类
       看一个需求:
                如下一个配置文件 mysql.properties:
                                        ip=192.168.0.13
                                        user=root
                                        pwd=12345
                                请问编程读取 ip 、user 和 pwd 的值是多少?



public class Properties01 {
        public static void main(String[] args) throws IOException {

                //读取mysql.properties 文件,并得到ip, user 和 pwd
                BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
                String line = "";
                while ((line = br.readLine()) != null) { //循环读取
                        String[] split = line.split("=");  //分隔符

                        //如果我们要求指定的ip值
                        if("ip".equals(split[0])) {
                                System.out.println(split[0] + "值是: " + split[1]);  //其他信息过滤掉

                        }
                }
                br.close();
        }
}

                提前创建:mysql.properties 文件。内容:
                                                ip=192.168.100.100
                                                user=root
                                                pwd=12345

传统方法弊端:提取指定信息,比较繁琐!!麻烦。比如:只获取ip,还那就要一个一个判断,麻烦。

//**************************************************************************************************************************//
//********************************************************************************640***************************************//
//**************************************************************************************************************************//
                                        properties 类
                        1)专门用于读写配置文件的集合类配置文件的格式:键=值键=值
                        2)注意: 键值对不需要有空格,值不需要用引号一起来。默认类型是String
                基本介绍:
                        3)Properties的常见方法
                        load: 加载配置文件的键值对到Properties对象
                        list:将数据显示到指定设备
                        getProperty(key):根据键获取值
                        setProperty(key;value):设置键值对到Properties对象
                        store:将Properties中的键值对存储到配置文件,在idea 中,保存信息到配置文件,如果含有中文,会存储为unicode码

                      "  http://tool.chinaz.com/tools/unicode.aspx   unicode码查询工具 "

//*********   使用Properties类完成对 mysql.properties 的读取,看老师代码演示
public class Properties02 {
        public static void main(String[] args) throws IOException {
                //使用Properties 类来读取mysql.properties 文件

                //1. 创建Properties 对象
                Properties properties = new Properties();
                //2. 加载指定配置文件
                properties.load(new FileReader("src\\mysql.properties"));

                温馨提示:找不到文件的把文件放项目的SRC不要放在包里的SRC

                //3. 把k-v显示控制台
                properties.list(System.out);
                //4. 根据key 获取对应的值
                String user = properties.getProperty("user");
                String pwd = properties.getProperty("pwd");
                System.out.println("用户名=" + user);
                System.out.println("密码是=" + pwd);



        }
}
//**************************************************************************************************************************//
//********************************************************************************641**************************************//
//**************************************************************************************************************************//
public class Properties03 {
        public static void main(String[] args) throws IOException {
                //使用Properties 类来创建 配置文件, 修改配置文件内容

                Properties properties = new Properties();
                //创建
                //1.如果该文件没有key 就是创建
                //2.如果该文件有key ,就是修改
        /*
            Properties 父类是 Hashtable , 底层就是Hashtable 核心方法
            public synchronized V put(K key, V value) {
                // Make sure the value is not null
                if (value == null) {
                    throw new NullPointerException();
                }

                // Makes sure the key is not already in the hashtable.
                Entry<?,?> tab[] = table;
                int hash = key.hashCode();
                int index = (hash & 0x7FFFFFFF) % tab.length;
                @SuppressWarnings("unchecked")
                Entry<K,V> entry = (Entry<K,V>)tab[index];
                for(; entry != null ; entry = entry.next) {
                    if ((entry.hash == hash) && entry.key.equals(key)) {
                        V old = entry.value;
                        entry.value = value;//如果key 存在,就替换
                        return old;
                    }
                }

                addEntry(hash, key, value, index);//如果是新k, 就addEntry
                return null;
            }

         */
                properties.setProperty("charset", "utf8");
                properties.setProperty("user", "汤姆");//注意保存时,是中文的 unicode码值
                properties.setProperty("pwd", "888888");

                //将k-v 存储文件中即可
                properties.store(new FileOutputStream("src\\mysql2.properties"), "麦合");
                System.out.println("保存配置文件成功~");

        }
}

                输出结果:
                        #麦合     //注释     null 的话,不会有注释
                        #Wed Dec 13 18:36:58 CST 2023
                        user=\u6C64\u59C6
                        pwd=888888
                        charset=utf8

//**************************************************************************************************************************//
//*********************************************************************************642************************************//
//**************************************************************************************************************************//
public class Homework01 {
        public static void main(String[] args) throws IOException {
                /**
                 *(1) 在判断e盘下是否有文件夹mytemp ,如果没有就创建mytemp
                 *(2) 在e:\\mytemp 目录下, 创建文件 hello.txt
                 *(3) 如果hello.txt 已经存在,提示该文件已经存在,就不要再重复创建了
                 *(4) 并且在hello.txt 文件中,写入 hello,world~

                 */

                String directoryPath = "e:\\mytemp";
                File file = new File(directoryPath);    // 创建目录
                if(!file.exists()) {
                        //创建
                        if(file.mkdirs()) {
                                System.out.println("创建 " + directoryPath + " 创建成功" );
                        }else {
                                System.out.println("创建 " + directoryPath + " 创建失败");
                        }
                }

                String filePath  = directoryPath + "\\hello.txt";// e:\mytemp\hello.txt
                file = new File(filePath);   //创建文件
                if(!file.exists()) {
                        //创建文件
                        if(file.createNewFile()) {
                                System.out.println(filePath + " 创建成功~");

                                //如果文件存在,我们就使用BufferedWriter 字符输入流写入内容
                                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
                                bufferedWriter.write("hello, world~~ 韩顺平教育");
                                bufferedWriter.close();

                        } else {
                                System.out.println(filePath + " 创建失败~");
                        }
                } else {
                        //如果文件已经存在,给出提示信息
                        System.out.println(filePath + " 已经存在,不在重复创建...");
                }


        }
}
//**************************************************************************************************************************//
//**********************************************************************************643*************************************//
//**************************************************************************************************************************//
public class Homework02 {
        public static void main(String[] args) {
                /**
                 * 要求:  使用BufferedReader读取一个文本文件,为每行加上行号,
                 * 再连同内容一并输出到屏幕上。
                 */

                String filePath = "e:\\a.txt";
                BufferedReader br = null;
                String line = "";
                int lineNum = 0;
                try {
                        br = new BufferedReader(new FileReader(filePath));

                        br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));  //如果目标文件是 ANSI (GBK)

                        while ((line = br.readLine()) != null) {//循环读取
                                System.out.println(++lineNum + line);
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                } finally {

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

//**************************************************************************************************************************//
//***********************************************************************************644************************************//
//**************************************************************************************************************************//
public class Homework03 {
        public static void main(String[] args) throws IOException {
                /**
                 * (1) 要编写一个dog.properties   name=tom age=5 color=red
                 * (2) 编写Dog 类(name,age,color)  创建一个dog对象,读取dog.properties 用相应的内容完成属性初始化, 并输出
                 * (3) 将创建的Dog 对象 ,序列化到 文件 e:\\dog.dat 文件
                 */
                String filePath = "src\\dog.properties";
                Properties properties = new Properties();
                properties.load(new FileReader(filePath));
                String name = properties.get("name") + ""; //Object -> String
                int age = Integer.parseInt(properties.get("age") + "");// Object -> int
                String color = properties.get("color") + "";//Object -> String

               // name: String name   age:int 5   color:String red

                Dog dog = new Dog(name, age, color);
                System.out.println("===dog对象信息====");
                System.out.println(dog);

                //将创建的Dog 对象 ,序列化到 文件 dog.dat 文件
                String serFilePath = "e:\\dog.dat";
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
                oos.writeObject(dog);

                //关闭流
                oos.close();
                System.out.println("dog对象,序列化完成...");
        }

        //在编写一个方法,反序列化dog
        @Test
        public void m1() throws IOException, ClassNotFoundException {
                String serFilePath = "e:\\dog.dat";
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));
                Dog dog = (Dog)ois.readObject();

                System.out.println("===反序列化后 dog====");
                System.out.println(dog);

                ois.close();

        }
}

class Dog implements Serializable {
        private String name;
        private int age;
        private String color;

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

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

        细节:提前写 dog.properties 文件。内容:
                                              name=tom
                                              age=5
                                              color=red

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值