Java模块学习——IO流

目录

# 关于IO流

  ## File构造方法

  ## 方法功能

  ## 文件名过滤器

  ## IO流分类

  ## IO流-字节流

  ### 字节输出流

  ### 字节输入流

  ### 缓冲输出流

  ### 缓冲输入流

  ## IO流-字符流

  ### 概念

  ### 字符输出流

  ### 字符输入流

  ### 字符缓冲输出流

  ### 字符缓冲输入流

  ### 缓冲流的特殊方法

  ## 案例


# 关于IO流

  ## File构造方法

    public class FileDemo {

    public static void main(String[] args) {

        //将一个目录封装成一个对象

        File file = new File("Z:\\test");

        //根据一个目录和一个子文件得到一个File对象

        File file1 = new File(file, "上课须知.txt");

        System.out.println(file);

        //从父路径名字字符串和子路径名字符串创建新的File

        File file2 = new File("Z:\\test", "上课须知.txt");

        System.out.println(file2);

        //创建File对象的原因:

        //对想要进行操作的文件或者文件夹,将其封装成一个File对象

        //然后调用该对象中的方法对文件或者文件夹进行操作

      }

    }

  ## 方法功能

public class FileDemo2 {

        public static void main(String[] args) {

            //创建File对象

            File file1 = new File("Z:\\test\\zxt.txt");

            //创建功能

            //创建文件

            boolean newFile1=false;

            try {

                newFile1 = file1.createNewFile();

            } catch (IOException e) {

                //如果想要创建的文件,没有指定的目录,就会报错

                //所以这里需要try...catch...

                e.printStackTrace();

            }

            System.out.println(newFile1);

            //创建文件夹

            File file2 = new File("Z:\\test\\zxt");

            boolean mkdir2 = file2.mkdir();

            System.out.println(mkdir2);


            //创建多级文件夹

            File file3 = new File("Z:\\test\\zxt1\\zxt1\\zxt1.txt");

            boolean mkdirs = file3.mkdirs();

            System.out.println(mkdirs);


            //删除功能:想要删除一个文件,这个文件夹里面的内容必须是空的

            file3.delete();


            //重命名功能

            file2.renameTo(new File("Z:\\test\\hahaha"));


            //判断功能

            //判断是否是一个目录

            file2.isDirectory();

            //判断是否是一个文件

            file2.isFile();

            //判断是否存在

            file2.exists();

            //判断是否可读

            file2.canRead();

            //判断是否可写

            file2.canWrite();

            //判断是否隐藏

            file2.isHidden();


            //绝对路径(完整路径):带有盘符的

            //相对路径:相对于一个目录开始(不带盘符的)


            //获取功能

            //获取绝对路径

            file2.getAbsolutePath();

            //获取相对路径

            file2.getPath();

            //获取名称

            file2.getName();

            //获取长度:(获取字节大小,文件属性中可以看见字节数 )

            file2.length();

            //获取最后一次修改的时间

            //返回的是时间戳,精确到毫秒

            file2.lastModified();

            //public Date(long date)  时间戳与日期的转换

            Date date = new Date((file2.lastModified()));

            System.out.println(date);


            //高级获取功能

            //获取指定目录下的所有文件或者文件夹的名称,组成一个数组

            String[] list = file2.list();

            System.out.println(list);

            for (String s : list) {

                System.out.println(s);

            }

            //获取指定目录下的所有文件或者文件夹组成的File数组

            File[] files = file2.listFiles();

            for (File f : files) {

                System.out.println(f);

            }

        }

    }

  ## 文件名过滤器

    public class test1 {

        public static void main(String[] args) {

            File file = new File("Z:\\test\\zxt");

            //方法一:用File数组,然后进经过遍历,如果符合要求就输出

    //        File[] files = file.listFiles();

    //        for (File f : files) {

    //            //判断是否是文件

    //            if (f.getName().endsWith(".png")) {

    //                System.out.println(f.getName());

    //            }

    //        }

            //在创建File数组时就进行判断(过滤器)

            File[] files = file.listFiles(new FilenameFilter() {

                //该目录下的文件或者文件夹是否加入到数组中

                //取决于这里的返回值是true还是flase

                @Override

                public boolean accept(File dir, String name) {

                    //return false;

                    File file1 = new File(dir, name);

                    boolean b1 = file1.isFile();

                    boolean b2 = file1.getName().endsWith(".png");

                    return b1 && b2;

                }

            });

            if (files != null) {

                for (File f : files) {

                    System.out.println(f.getName());

                }

            }

        }

    }    

  ## IO流分类

    流向:(以java程序为中心)  

        输入流  读取数据

        输出流  写出数据

    数据类型:  

        字节流:

            字节输入流  读取数据  InputStream

            字节输出流  写出数据  OutputStream

        字符流:

            字符输入流  读取数据  Reader

          字符输出流  写出数据  Writer

      怎么区分字节流还是字符流?

        用windows自带的记事本打开,如果看不懂就用字节流,如果看的懂,就用字符流

      (字节流可以读取任何数据)(注意这里 看不懂!=乱码)

  ## IO流-字节流

  ### 字节输出流

    public class FileOutputStreamDemo02 {

    //        字节输出流操作步骤

    //          1、创建字节输出流对象

    //          2、调用write方法写入数据

    //          3、释放资源

        public static void main(String[] args) {

            try {

                //创建字节输出流

                FileOutputStream fileOutputStream = new FileOutputStream("b.txt");

                //调用write方法写入数据

                //void write(int b)将指定的字节写入此文件输出流

                //存储的是int数据对应的ASCII码值

                fileOutputStream.write(98);

                fileOutputStream.write(97);

                fileOutputStream.write(99);

                //void write(int[] b)将b.length个字节从指定的字节数组写入此文件输出流

                byte[] bytes = {100, 101, 102,103};

                fileOutputStream.write(bytes);

                //void write(int[] b,int off,int len)将len字节从位于偏移量off的指定字节数组写入此文件输出流

                fileOutputStream.write(bytes, 1, 3);

                //1、进行换行

                //Windows:\r\n

                //Mac:\r

                //Linux:\n

                //2、实现追加写入

                //创建时,在后面加true,就是追加写入

                FileOutputStream fileOutputStream1 = new FileOutputStream("b.txt",true);

                //追加:在原有的文件内容上继续添加新的内容

                //覆盖:将原有的文件内容删掉,再添加新的内容

                for (int i = 0; i < 10; i++) {

                    fileOutputStream.write(("大数据,yyds" + i).getBytes());

                    fileOutputStream.write("\r\n".getBytes());

                }

                fileOutputStream.close();

                for (int i = 0; i < 10; i++) {

                    fileOutputStream1.write(("大数据,yyds" + i).getBytes());

                    fileOutputStream1.write("\r\n".getBytes());

                }

                fileOutputStream1.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    }

  ### 字节输入流

    public class FileInputStreamDemo {

        //字节输入流操作步骤

        //   1、创建字节输入流对象

        //   2、调用read()方法读取数据,输出到控制台

        //   3、释放资源

        public static void main(String[] args) {

            try {

                //创建字节输入流对象

                FileInputStream fileInputStream = new FileInputStream("b.txt");

                //调用read()方法读取数据,输出到控制台

               

                //方式一:int read() 从该输入流读取一个字节的数据

                System.out.println(((char)fileInputStream.read()));

                //用while循环改进,读到文件末尾停止

                //由API知如果达到文件末尾,-1

                int b = 0;

                while (( b=fileInputStream.read()) != -1) {

                    System.out.println((char) b);

                }

                //方式二:int read(byte[] b)从该输入流读取b.length个字节数据的字节数组

                //开发中这里数组的长度最好是1024的长度,因为刚好是1kb

                byte[] bytes = new byte[1024];

                //返回的是实际读取到的字节的长度

                int length = 0;

                //用while循环改进,读取到文件末尾,由API知道文件末尾为-1

                while ((length = fileInputStream.read()) != -1) {

                    //这里把字符数组转为字符串

                    String s = new String(bytes, 0, length);

                    System.out.println(s);

                }

                fileInputStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  ### 缓冲输出流

    public class BufferedOutputStreamDemo {

        //缓冲区类(高效类):高效读写

        //字节缓冲输出流  BufferedOutputStream

        //字节缓冲输入流  BufferedInputStream

        public static void main(String[] args) {

            //BufferedOutputStream

            //创建一个新的缓冲输出流,以将数据写入指定的底层输出流

            try {

                //开发中推荐用此方法创建

                java.io.BufferedOutputStream bufferedOutputStream = new java.io.BufferedOutputStream(new FileOutputStream("a.txt"));

                //往文件中写入数据

                bufferedOutputStream.write("大数据yyds".getBytes());

                //释放资源

                //关闭的时候,关闭之前也对缓冲区进行了一次刷新

                bufferedOutputStream.close();

                //bufferedOutputStream.flush();  //这条语句就是对缓冲区刷新

                //只有对缓冲区刷新,写入的数据才可以显示

                //bufferedOutputStream.write("数加科技".getBytes());  //这时已经被关闭,数据就不能被写入了

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  ### 缓冲输入流

    public class BufferedInputStreamDemo {

        //缓冲区类(高效类):高效读写

        //字节缓冲输出流  BufferedOutputStream

        //字节缓冲输入流  BufferedInputStream

        //问题:一个一个字节去读取中文时,强转之后会可能出现看不懂的字符(不是乱码)

        //但是用String就不会出现者种情况,是因为没有发生强转,new String内部有一套固定的编码

       

        public static void main(String[] args) {

            //BufferedInputStream

            //创建一个BufferedInputStream并保存其参数,输入流in,供以后使用

            try {

                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("a.txt"));

                //一次读取一个字节

                int b = 0;

                while ((b = bufferedInputStream.read()) != -1) {

                    System.out.println((char) b);

                }

                System.out.println("==============================");

                //一次读取一个字节数组

                byte[] bytes = new byte[1024];

                int length = 0;

                while ((length = bufferedInputStream.read(bytes)) != -1) {

                    System.out.println(new String(bytes, 0, length));

                }

                bufferedInputStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  ## IO流-字符流

  ### 概念

    字符流 = 字节流 + 编码表

    OutputStreamWrite = FileOutputStream + 编码表(Unicode)

    InputStreamReader = FileInputStream + 编码表(Unicode)

    (正常做字符流的处理的时候,一般不会刻意传入编码,用的都是默认的编码(Unicode))

    字符转换流的简化写法

        字符输出流:

            FileWrite

        字符输入流:

            FileReader

  ### 字符输出流

    public class OutputStreamWriterDemo2 {

      //Writer():(java提供操作字符流的父类)

          //OutputStreamWriter  字符输出流(字符转换流)

            //OutputStreamWriter(OutputStream out)

              //创建一个使用默认字符编码的OutputStreamWriter

            //OutputStreamWriter((OutputStream out,String charsetName)

              // 创建一个使用命名字符集的OutputStreamWriter

        public static void main(String[] args) {

            try {

                OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d.txt"));

                //public void write(int c)

                //一次写一个字符

                osw.write(99);

                osw.flush();

                //public void write(char[] cbuf)

                //一次写一个字符数组

                char[] chars = {'a', 'b', 'c', 'd'};

                osw.write(chars);

                osw.flush();

                //public void write(char[] cbuf,int index,int length)

                //一次写入字符数组的一部分

                osw.write(chars, 1, 2);

                osw.flush();

                //public void write(String str)

                //一次写入一个字符串

                osw.write("大数据yyds");

                osw.flush();

                //public void write(String str,int off,int len)

                //一次写入字符串的一部分(字符串底层其实也是一个字符数组,也有下标)

                osw.write("大数据yyds", 0, 3);

                osw.flush();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  ### 字符输入流

    public class InputStreamReaderDemo2 {

        //Reader:字符流的父类

          //InputStreamReader:字符输入流

            //InputStreamReader(InputStream in)

              //创建一个使用默认字符集的InputStreamReader

            //InputStreamReader(InputStream in,String charsetName)

              //创建一个使用命名字符集的InputStreamReader

        public static void main(String[] args) {

            try {

                //创建字符输入流对象

                InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("d.txt"));

                //读取数据

    //           public int read()    //一次读取一个字符

    //            int c = 0;

    //            while ((c = inputStreamReader.read()) != -1) {

    //                System.out.println((char) c);

    //            }

    //            public int read(char[] cbuf)  //一次读取一个字符数组

                char[] cbuf = new char[1024];

                int length = 0;

                while ((length = inputStreamReader.read(cbuf)) != -1) {

                    System.out.println(new String(cbuf, 0, length));

                }

                inputStreamReader.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  ### 字符缓冲输出流

    public class BufferedWriteDemo {

        //缓冲区类(高效类):高效读写

        //字符缓冲输出流  BufferedWriter

        //字符缓冲输入流  BufferedReader

        //BufferedWriter:

        //将文本写入字符输出流,缓冲字符,以提供单个字符,数组和字符串的高效写入

        //可以指定缓冲区大小,或者可以接受默认大小

        public static void main(String[] args) {

            try {

                //创建字符缓冲输出流

                //BufferedWriter (Writer out)

                //简化写法

                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("f.txt"));

                bufferedWriter.write("hello");

                bufferedWriter.write("\r\n");

                bufferedWriter.write("world");

                bufferedWriter.flush();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  ### 字符缓冲输入流

    public class BufferedReaderDemo {

        //缓冲区类(高效类):高效读写

        //字符缓冲输出流  BufferedWriter

        //字符缓冲输入流  BufferedReader

        //BufferedReader:

        //创建使用默认大小的输入缓冲区的缓冲字符输入流

        public static void main(String[] args) {

            //创建字符缓冲输入流

            //BufferedReader (Reader in)

            //简化写法

            try {

                BufferedReader bufferedReader = new BufferedReader(new FileReader("f.txt"));

                char[] ch = new char[1024];

                int length = 0;

                while ((length = bufferedReader.read(ch)) != -1) {

                    System.out.println(new String(ch, 0, length));

                }

                bufferedReader.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  ### 缓冲流的特殊方法

    public class BufferSpecialFunctionDemo {

        public static void main(String[] args) {

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

            File file1 = new File("h.txt");

            wirte();

            read(file);

            copy(file, file1);

        }

        public static void copy(File file1, File file2) {

            //字符流缓冲流特殊功能复制文件(注:其他的只需要用常规方式在数据源读取,再写入目的地)

            //例:从file1复制到file2

            try {

                BufferedReader bufferedReader = new BufferedReader(new FileReader(file1));

                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file2));

                String line ;

                while ((line = bufferedReader.readLine()) != null) {

                    bufferedWriter.write(line);

                    bufferedWriter.newLine();

                }

                bufferedWriter.close();

                bufferedReader.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        public static void read(File file) {

            try {

                BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

                //readLine():每次读取一行,返回String类型

    //            String s1 = bufferedReader.readLine();

    //            System.out.println(s1);

    //            String s2 = bufferedReader.readLine();

    //            System.out.println(s2);

                //用while循环改进(常用)

                String line ;

                while (((line) = bufferedReader.readLine()) != null) {

                    System.out.println(line);

                }

                bufferedReader.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        public static void wirte(){

            try {

                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("g.txt"));

                bufferedWriter.write("hello");

                //newLine():自动识别设备,执行换行

                bufferedWriter.newLine();

                bufferedWriter.write("world");

                bufferedWriter.flush();

            } catch (IOException e) {

                e.printStackTrace();

            }

        };

    }

  ## 案例

    /**

    * @author 小菜鸡

    * @date 2021/12/28 22:31

    * @description

    *     需求:键盘录入5个学生信息(姓名,成绩,性别),按照总分从高到低存入文本文件

    */

    public class IOTest2 {

        public static void main(String[] args) {

            //创建Scanner对象

            Scanner scanner = new Scanner(System.in);

            //创建集合存储学生对象

            //由于需要从高到低排序,优先选择TreeSet

            TreeSet<Student1> list = new TreeSet<>(new Comparator<Student1>() {

                @Override

                public int compare(Student1 o1, Student1 o2) {

                    //按照总分从高到底排列

                    int i = o2.getScore() - o2.getScore();

                    //总分一样,语文成绩不一定一样,按语文成绩从高到低

                    int i2 = i == 0 ? o2.getChinese() - o1.getChinese() : i;

                    //总分一样,语文成绩一样,数学成绩不一定一样,按数学成绩从高到低

                    int i3 = i2 == 0 ? o2.getMath() - o1.getMath() : i2;

                    //各科成绩都一样,名字不一定一样

                    int i4 = i3 == 0 ? o2.getName().compareTo(o1.getName()) : i3;

                    return i4;

                }

            });

            System.out.println("===========开始录入学生信息============");

            for (int i = 1; i < 5; i++) {

                System.out.println("请输入第"+i+"个学生信息");

                Student1 student1 = new Student1();

                System.out.println("姓名:");

                student1.setName(scanner.next());

                System.out.println("语文成绩:");

                student1.setChinese(scanner.nextInt());

                System.out.println("数学成绩:");

                student1.setMath(scanner.nextInt());

                System.out.println("英语成绩:");

                student1.setEnglish(scanner.nextInt());

                list.add(student1);

            }

            System.out.println(list);

            try {

                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("学生成绩排序.txt"));

                bufferedWriter.write("==============学生成绩如下================");

                bufferedWriter.newLine();

                for (Student1 student1 : list) {

                    bufferedWriter.write(student1.getName() + "\t" + student1.getChinese() + "\t" + student1.getMath() + "\t" + student1.getEnglish() + "\t" + student1.getScore());

                    bufferedWriter.newLine();

                }

                bufferedWriter.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

    class Student1 {

        private String name;

        private int chinese;

        private int math;

        private int english;

        private int score;

        public Student1(String name, int chinese, int math, int english) {

            this.name = name;

            this.chinese = chinese;

            this.math = math;

            this.english = english;

        }

        public Student1() {

        }

        public String getName() {

            return name;

        }

        public void setName(String name) {

            this.name = name;

        }

        public int getChinese() {

            return chinese;

        }

        public void setChinese(int chinese) {

            this.chinese = chinese;

        }

        public int getMath() {

            return math;

        }

        public void setMath(int math) {

            this.math = math;

        }

        public int getEnglish() {

            return english;

        }

        public void setEnglish(int english) {

            this.english = english;

        }

        public int getScore() {

            score = math + chinese + english;

            return score;

        }

        @Override

        public String toString() {

            return "Student1{" +

                    "姓名:'" + name + '\'' +

                    ", 语文成绩:" + chinese +

                    ", 数学成绩:" + math +

                    ", 英语成绩" + english +

                    ", 总分" + score +

                    '}';

        }

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值