Java笔记--I/O系统

只有那些勇敢镇定的人,才能熬过黑暗,迎来光明。"

                                                                                                                     --玛格丽特《飘》

一、File类

File类的概述:

是所有文件和目录路径的抽象表示

构造方法:

public File(String pathname)

public File(String parent, String child)

public File(File parent,String child)

知识点:

路径:

  • 绝对路径(完整路径):指的是带有盘符的路径【在windows】
  • 举例:D:\projects\IDEAProjects\bigdata31-java\src\com\day16\data\a.txt
  • 相对路径:相对于该项目而言,将该项目作为开始
  • src/com/day16/data/a.txt
package day16;

import java.io.File;
/*
File: 是所有文件或者文件夹的路径抽象表现形式

    构造方法:
        public File(String pathname)
        public File(String parent,String child)
        public File(File parent,String child)
*/

public class FileDemo1 {
    public static void main(String[] args) {
        //将未来要操作的路径封装成File对象
        /*
            路径:
                绝对路径(完整的路径):是指带有盘符的路径【在windows】
                举例:E:\Java\idea_javasubject\bigdata\src\com\day16\data\a.txt
                相对路径:是指相对于项目而言,将该项目作为根
                举例:src/com/day16/data/a.txt
         */

        File file = new File("E:\\Java\\idea_javasubject\\bigdata\\src\\com\\shujia\\day16\\data\\a.txt");
        System.out.println(file);

        //也可以将一个不存在的文件封装成对象
        File file1 = new File("E:\\Java\\idea_javasubject\\bigdata\\src\\com\\shujia\\day16\\data\\b.txt");
        System.out.println(file1);

        //也可以传相对路径
        File file2 = new File("src/com/shujia/day16/data/a.txt");
        System.out.println(file2);

        //第二种创建方法 public File(String parent,String child)
        File file3 = new File("E:\\Java\\idea_javasubject\\bigdata\\src\\com\\shujia\\day16\\data\\", "a.txt");
        System.out.println(file3);

        //第三种创建方法 public File(File parent,String child)
        File file4 = new File(new File("E:\\Java\\idea_javasubject\\bigdata\\src\\com\\shujia\\day16\\data\\"), "a.txt");
        System.out.println(file4);
    }
}

 File种类的成员方法:

创建功能:

        public boolean createNewFile()

        public boolean mkdir() public

        boolean mkdirs()

删除功能:

         public boolean delete()

重命名功能:

        public boolean renameTo(File dest)

package day16;

import java.io.File;

/*
    File类种的成员方法:
        创建功能:
            public boolean createNewFile()
            public boolean mkdir()
            public boolean mkdirs()
        删除功能:
            public boolean delete()
        重命名功能:
            public boolean renameTo(File dest)


*/
public class FileDemo2 {
    public static void main(String[] args) throws Exception  {
        //E:\bigdata\111.text
        File file = new File("E:\\bigdata\\111.txt");

        //public boolean createNewFile()创建一个文件,若文件已经存在,返回false,否则创建文件返回true
        System.out.println(file.createNewFile());

        //public boolean mkdir()  创建目录
        File file1 = new File("E:\\bigdata\\aaa");
        System.out.println(file1.mkdir());

        //错误示范  报错mkdir()只能创建单级目录
        File file2 = new File("E:\\bigdata\\aaa\\bbb\\ccc\\");
        System.out.println(file2.mkdir());

        //public boolean mkdirs()创建多级目录
        System.out.println(file2.mkdirs());

        //public boolean delete()既可以删除文件,又可以删除某一个文件夹,但是delete()方法只能删除单级文件夹
        File file3 = new File("E:\\bigdata\\222.txt");
        System.out.println(file3.delete());

        //public boolean renameTo(File dest) 对文件或者文件夹进行重命名
        File file4 = new File("E:\\bigdata\\333.txt");
        System.out.println(file.renameTo(file4));
    }
}

File种类的判断功能:

判断功能

        public boolean isDirectory()

        public boolean isFile()

        public boolean exists()

        public boolean canRead()

        public boolean canWrite()

        public boolean isHidden()

package day16;

/*
    判断功能
        public boolean isDirectory()
        public boolean isFile()
        public boolean exists()
        public boolean canRead()
        public boolean canWrite()
        public boolean isHidden()

*/

import java.io.File;

public class FileDemo3 {
    public static void main(String[] args) {
        File file = new File("E:\\bigdata\\333.txt");

        //public boolean isDirectory()是否是文件夹
        System.out.println(file.isDirectory());

        //public boolean isFile()是否是文件
        System.out.println(file.isFile());

        //public boolean exists()是否存在
        System.out.println(file.exists());

        //public boolean canRead()是否可读
        System.out.println(file.canRead());

        // public boolean canWrite()是否可写
        System.out.println(file.canWrite());

        //public boolean isHidden()
        System.out.println(file.isHidden());
    }
}

 File种类的基本获取功能:

基本获取功能

        public String getAbsolutePath()

        public String getPath()

        public String getName()

        public long length()

        public long lastModified()

package day16;

/*
基本获取功能
    public String getAbsolutePath()
    public String getPath()
    public String getName()
    public long length()
    public long lastModified()

*/

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileDemo4 {
    public static void main(String[] args) {
        File file = new File("src/com/day16/data/a.txt");

        //  public String getAbsolutePath()获取文件的绝对路径
        System.out.println(file.getAbsoluteFile());

        System.out.println(file.getPath());//获取文件的相对路径

        System.out.println(file.getName());//获取文件或者文件夹的名字、

        System.out.println(file.length());//获取文件内容字节数

        File file1 = new File("E:\\bigdata\\333.txt");
        long l = file1.lastModified();//最近一次修改时间
        Date date = new Date(l);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String time = simpleDateFormat.format(date);
        System.out.println("上次修改的时间:"+time);
    }
}

File种类的高级获取功能:

高级获取功能

        public String[] list()

        public File[] listFiles()

package day16;

/*

高级获取功能
    public String[] list()
    public File[] listFiles()

*/

import java.io.File;
import java.util.Arrays;

public class FileDemo5 {
    public static void main(String[] args) {
        File file = new File("src/com/shujia/day16");


        //public String[] list()列出当前目录下所有的文件及文件夹的名称,组成数组
        String[] names = file.list();
        System.out.println(Arrays.toString(names));

        //public File[] listFiles()  列出当前目录下所有的文件及文件夹的File对象
        File[] files = file.listFiles();

        //消除警告的第一种方法
        //        assert files != null;//这种方式叫断言
//        for (File file1 : files){
//            System.out.println(file1);
//        }

        if(files!=null){//消除警告的
            for(File file1: files){
                System.out.println(file1);
            }
        }
    }
}

 二、I/O流概述

按照类型划分:

        字节流(万能流):

                字节输出流:

                        OutputStream(抽象类)

                                -- 实现子类:FileOutputStream

                                -- 实现子类:字节缓冲输出流:BufferedOutputStream

                字节输入流:

                        InputStream(抽象类)

                                -- 实现子类:FileInputStream

                                -- 实现子类:字节缓冲输入流:BufferedInputStream

        字符流:

                字符输入流:

                        Reader(抽象类)

                                -- 实现子类:InputStreamReader

                                -- 实现子类:字符缓冲输入流:BufferedReader
                       

                字符输出流:

                        Writer (抽象类)

                                -- 实现子类: OutputStreamWriter

                                -- 实现子类: 字符缓冲输出流:BufferedWriter

1、字节流

字节流(万能流):

                字节输出流:

                        OutputStream(抽象类)

                                -- 实现子类:FileOutputStream

                                -- 实现子类:字节缓冲输出流:BufferedOutputStream

                字节输入流:

                        InputStream(抽象类)

                                -- 实现子类:FileInputStream

                                -- 实现子类:字节缓冲输入流:BufferedInputStream

(1)字节输出流:FileOutputStream

构造方法

FileOutputStream:

        FileOutputStream(File file)

        FileOutputStream(String name)

package day16;
/*
    I/O流:输入输出流
    按照流向划分:
        输入流:将外部存储数据 --> Java
        输出流:Java --> 外部存储工具中

    按照类型划分:
        字节流(万能流):
            字节输入流:
                OutputStream(抽象类)
                    -- 实现子类:FileOutputStream
            字节输出流:
                InputStream
        字符流:
            字符输入流:
            字符输出流:

    FileOutputStream:
    FileOutputStream(File file)
    FileOutputStream(String name)

    需求:往一个文本文件中写一句话:“helloworld”
*/
import java.io.FileOutputStream;
public class FileOutputStreamDemo1 {
    public static void main(String[] args) throws Exception{
        //FileOutputStream(File file) 需要先将目标文件封装成一个File对象放入到构造方法
//        File file = new File("src/com/shujia/day16/data/a2.txt");
//        //若写入的目标文件不存在的话,会自动创建一个
//        FileOutputStream fos = new FileOutputStream(file);
        //FileOutputStream(String name)
        FileOutputStream fos = new FileOutputStream("src/com/day16/data/a2.txt");
        System.out.println(fos);
    }
}

 字节流写入数据的方式

        public void write(int b)

        public void write(byte[] b)

        public void write(byte[] b,int off,int len)

思考:
        1、怎么实现追加写?

package day16;

import java.io.FileOutputStream;
import java.io.IOException;

/*
    public void write(int b)
    public void write(byte[] b)
    public void write(byte[] b,int off,int len)

    思考:
        1、怎么实现追加写?
 */
public class FileOutputStreamDemo2 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream("src/com/day16/data/a3.txt");
            //public void write(int b)
            //写一个字符
            fos.write(97);
            fos.write(98);
            fos.write(99);
            fos.write(100);
            fos.write("\r\n".getBytes());
            //public void write(byte[] b) //一次写一个字节数组
            byte[] bytes = {97,98,119,120,101,102};
            fos.write(bytes);
            fos.write("\r\n".getBytes());
            //public void write(byte[] b,int off,int len) 一次写字节数组的一部分
            fos.write(bytes,2,2);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            //释放写数据资源
            if(fos!=null){
                try{
                    fos.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

2、怎么实现换行

package com.day16;
import java.io.FileOutputStream;
/*
    思考:
        1、怎么实现追加写?
        2、怎么实现换行?
 */
public class FileOutputStreamDemo3 {
    public static void main(String[] args)throws Exception {
        //若文件已经存在,会将文件中的内容清空,若想要实现追加,在传如路径之后,append属性给true
        FileOutputStream fos = new FileOutputStream("src/com/day16/data/a3.txt",true);
        fos.write(110);
        fos.write(111);
        fos.write(112);
        fos.write("\r\n".getBytes());
        fos.close();
//        fos.write(113);
        //释放资源之后无法再继续使用了
    }
}
(2)字节输入流:FileInputStream

构造方法:

FileInputStream(File file)

FileInputStream(String name)

package day16;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/*
    字符输入流:FileInputStream
    构造方法

    FileInputStream(File file)
    FileInputStream(String name)

 */
public class FileInputStreamDemo1 {
    public static void main(String[] args) throws Exception{
        //FileInputStream(File file)将要进行的读取的文件封装成File对象放入构造方法中
        //输入必要要求目标文件要已经存在,不然报错
//        File file = new File("src/com/day16/data/a4.txt");
//        FileInputStream fis  = new FileInputStream(file);
        //FileInputStream(String name)
        FileOutputStream fos = new FileOutputStream("src/com/day16/data/a4.txt");
        byte[] bytes ={100,101,102,103};
        fos.write(bytes);
        FileInputStream fis = new FileInputStream("src/com/day16/data/a4.txt");


        fis.close();
    }
}

FileInputStream读数据的方法

        public int read()

        public int read(byte[] b)

package day16;


import java.io.FileInputStream;

/*

    FileInputStream读数据的方法;
        public int read()
        public int read(byte[] b)

 */
public class FileInputStreamDemo2 {
    public static void main(String[] args) throws Exception{
        //创建字节输入流对象
        FileInputStream fis = new FileInputStream("src/com/day16/data/a2.txt");

//        //public int read()  每次只读第一个字符
//        System.out.print((char)fis.read());
//        System.out.print((char)fis.read());
//        System.out.print((char)fis.read());
//        System.out.print((char)fis.read());
//        System.out.print((char)fis.read());
//        System.out.print(fis.read());
//        int i=0;
//        while((i=fis.read())!=-1){
//            System.out.print((char)i);
//        }

        //public int read(byte[] b)
        //创建一个字节数组  一般的取值是1024的倍数
//        byte[] bytes = new byte[1024];
//        int length = fis.read(bytes);//返回的是实际读取的字节数
//        System.out.println(length);
//        String s = new String(bytes,0,length);
//        System.out.println(s);

//        byte[] bytes = new byte[10];
//        //第一次读
//        int length = fis.read(bytes);//返回的是实际读取的字节数
//        System.out.println(length);
//        //字节数组转字符串
//        String s = new String(bytes,0,length);
//        System.out.println(s);

//        //第二次读
//        int length1 = fis.read(bytes);//返回的是实际读取的字节数
//        System.out.println(length1);
//        //字节数组转字符串
//        String s1 = new String(bytes,0,length1);
//        System.out.println(s1);

//        //第二次读
//        int length2 = fis.read(bytes);//返回的是实际读取的字节数
//        System.out.println(length2);
//        //字节数组转字符串
//        String s2 = new String(bytes,0,length2);
//        System.out.println(s2);

        //使用while循环读取
        byte[] bytes = new byte[1024];
        int length = 0;
        while((length=fis.read(bytes))!=-1){
            String s = new String(bytes,0,length);
            System.out.println(s);
        }
        //释放资源
        fis.close();
    }
}
(3)字节缓冲输出流:BufferedOutputStream

构造方法:

BufferedOutputStream(OutputStream out) 创建一个新的缓冲输出流,以将数据写入指定的底层输出流

package day17.Study;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
/*
    java针对字节输入流和字节输出流都提供了相应的缓冲流来提高读写的速度
    字节流:
        输入流:
            InputStream
                - FileInputStream
                - BufferedInputStream(字节缓冲输入流)
        输出流:
            OutputStream
                - FileOutputStream
                - BufferedOutputStream(字节缓冲输出流)
    字节缓冲输出流:BufferedOutputStream
        构造方法:
            BufferedOutputStream(OutputStream out) 创建一个新的缓冲输出流,以将数据写入指定的底层输出流
 */
public class BufferedOutputStreamDemo1 {
    public static void main(String[] args) throws Exception{
        //创建字节缓冲输出流对象,向文件中写数据
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src/com/day17/data1/a3.txt"));
//        bos.write(97);
//        bos.flush();
//        bos.write("今天的天气真好".getBytes());
//        bos.flush();
        byte[] bytes = {97,98,99,100,101,102};
        bos.write(bytes,2,2);
        bos.flush();
        bos.close();
    }
}
(4)字节缓冲输入流:BufferedInputStream

构造方法:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("路径"));

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

package day17.Study;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
/*
    字节缓冲输入流:BufferedInputStream
        构造方法:BufferedInputStream bis  = new BufferedInputStream(new FileInputStream("路径"));
        创建一个BufferedInputStream并保存其参数,输入流in,供以后使用
 */
public class BufferedInputStreamDemo1 {
    public static void main(String[] args) throws Exception {
        //创建一个字节缓冲输入流对象读取数据
        BufferedInputStream bis  = new BufferedInputStream(new FileInputStream("src/com/day17/data1/a2.txt"));
        //一次读取一个字节
        int i = 0;
        while((i = bis.read())!=-1){
            System.out.print((char) i);
        }
        //一次读取一个字节数组
        byte[] bytes = new byte[1024];
        int length = 0;
        while((length = bis.read(bytes))!=-1){
            String s = new String(bytes,0,length);
            System.out.println(s);
        }
        bis.close();
    }
}

2、字符流

转换流(字符流) = 字节流 + 编码表

字符流:(当一个文件使用记事本打开可以直接看懂的时候,就可以使用字符流)

                字符输入流:

                        Reader(抽象类)

                                -- 实现子类:InputStreamReader

                                -- 实现子类:字符缓冲输入流:BufferedReader
                       

                字符输出流:

                        Writer (抽象类)

                                -- 实现子类: OutputStreamWriter

                                -- 实现子类: 字符缓冲输出流:BufferedWriter

(1)字符输出流:OutoutStreamWriter

构造方法:

OutputStreamWriter(OutputStream out) 构建一个使用默认字符编码的OutputStreamWriter. public OutputStreamWriter(OutputStream out,String charsetName) 创建一个使用命名字符集的OutputStreamWriter.

成员方法:

public void write(int c)

public void write(char[] cbuf)

public void write(char[] cbuf,int off,int len)

public void write(String str)

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

package day17.Study;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

/*

    转换流(字符流) =  字节流 + 编码表
    字符流:(当一个文件使用记事本打开可以直接看懂的时候,就可以使用字符流)
        字符输入流:
            Reader
        字符输出流:
            Writer
                -OutputStreamWriter(实现子类)

OutputStreamWriter:
    构造方法:
        OutputStreamWriter(OutputStream out) 构建一个使用默认字符编码的OutputStreamWriter.
        public OutputStreamWriter(OutputStream out,String charsetName) 创建一个使用命名字符集的OutputStreamWriter.
    成员方法:
        public void write(int c)
        public void write(char[] cbuf)
        public void write(char[] cbuf,int off,int len)
        public void write(String str)
        public void write(String str,int off,int len)


 */
public class OutputStreamWriterDemo1 {
    public static void main(String[] args) throws Exception{
//        String info = "今天是疯狂星期四,V我50块钱,我是秦始皇";
//        //编码
        byte[] bytes = info.getBytes();
//        //public byte[] getBytes(String charsetName)  指定编码转字节数组
//        byte[] bytes = info.getBytes("GBK");
//        System.out.println(Arrays.toString(bytes));
//        //解码
//        //String s = new String(bytes);
//        //public String(byte bytes,String charsetName) 指定编码将字节数组转字符串
//        String s = new String(bytes, "GBK");
//        System.out.println(s);
//        OutputStreamWriter(OutputStream out) 构建一个使用默认字符编码的OutputStreamWriter.
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/com/day17/data1/data11/a1.txt"));
        //public OutputStreamWriter(OutputStream out,String charsetName) 创建一个使用命名字符集的OutputStreamWriter.
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/com/day17/data1/data11/a1.txt"),"GBK");
        //public void write(int c)一次写一个ASCII码字符
//        osw.write(97);
//        osw.flush();
        //public void write(char[] cbuf)一次写一个字符数组
//        char[] chars = {'我','爱','中','国'};
//        osw.write(chars);
//        osw.flush();
        //public void write(char[] cbuf,int off,int len)一次写字符数组的一部分
//        osw.write(chars,2,2);
//        osw.flush();
        //public void write(String str) 一次写一个字符串
//        osw.write("我爱中国999");
//        osw.flush();
        //public void write(String str,int off,int len) 一次写字符串的一部分
        osw.write("我是秦始皇,V我50块钱",6,6);
        osw.write("\r\n");
        osw.write("其实今天是疯狂星期四");
        osw.flush();
        osw.close();
    }
}
(2)字符输入流:InputStreamReader

构造方法:

InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader. InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader。

成员方法:

public int read()

public int read(char[] cbuf)

package day17.Study;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/*
 转换流(字符流) =  字节流 + 编码表
    字符流:(当一个文件使用记事本打开可以直接看懂的时候,就可以使用字符流)
        字符输入流:
            Reader
                - InputStreamReader(实现子类)
        字符输出流:
            Writer
                -OutputStreamWriter(实现子类)
字符输入流:
    构造方法:
       InputStreamReader(InputStream in)  创建一个使用默认字符集的InputStreamReader.
       InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader。

    成员方法:
        public int read()
        public int read(char[] cbuf)
 */
public class InputStreamReaderDemo1 {
    public static void main(String[] args) throws Exception{
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/com/day17/data1/a3.txt"),"GBK");
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/com/day17/data1/data11/a1.txt"),"GBK");
        InputStreamReader isr = new InputStreamReader(new FileInputStream("src/com/day17/data1/a2.txt"),"GBK");
//        osw.write("笑傲江湖" );
//        osw.flush();
        //创建字符输入流对象
        //InputStreamReader isr = new InputStreamReader(new FileInputStream("src/com/shujia/day17/data1/a2.txt"));
//        InputStreamReader isr = new InputStreamReader(new FileInputStream("src/com/shujia/day17/data1/a3.txt"), "GBK");
        //public int read()
//        System.out.println((char)isr.read());
//        System.out.println((char)isr.read());
//        System.out.println((char)isr.read());
//        System.out.println((char)isr.read());

//        int i = 0;
//        while((i=isr.read())!=-1){
//            System.out.println((char)i);
//        }
//        osw.close();
        //public int read(char[] cbuf) 一次读取一个字符数组大小的字符,返回
        char[] chars = new char[1024];
        int length = 0;
        while((length=isr.read(chars))!=-1){
            String s = new String(chars, 0, length);
            System.out.print(s);
        }
        isr.close();
    }
}
(3)字符缓冲输出流:BufferedWriter(常用)

构造方法:

BufferedWriter(Writer out) 创建使用默认值的输入缓冲区的缓冲字符输出流

特殊的成员方法:

public void newLine() 自动根据当前系统所处的系统生成一个换行符

 因为构造方法过于困难,Java提供简单的简单的构建方法(字符缓冲输入流同理)

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(newFileOutputStream("D:\\Test.txt")));

------------------------->简化后--------------------------------->

BufferedWriter bw = new BufferedWriter(new FileWriter(""D:\\Test.txt""));

package day17.Study;
import java.io.BufferedWriter;
import java.io.FileWriter;
/*

字符流:(当一个文件使用记事本打开能看懂的时候,就可以使用字符流)
        字符输入流:
            Reader
                - InputStreamReader
                    -FileReader
                - BufferedReader(字符缓冲输入流)
        字符输出流:
            Writer
                - OutputStreamWriter
                    - FileWriter
                - BufferedWriter(字符缓冲输出流)
字符缓冲输出流:BufferedWriter
    构造方法:
        BufferedWriter(Writer out) 创建使用默认值的输入缓冲区的缓冲字符输出流
    特殊的成员方法:
        public void newLine() 自动根据当前系统所处的系统生成一个换行符
 */
public class BufferedWriterDemo1 {
    public static void main(String[] args) throws Exception{
        //创建字符缓冲输出对象
//        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\Test.txt")));
        //使用简化写法创建
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\Test.txt"));
        //写十行Hello World
        for(int i = 0; i < 10; i++){
            bw.write("hello world");
//            bw.write("\r\n");
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }
}
(4)字符缓冲输入流:BufferedReader(常用)

构造方法:

BufferedReader(Reader in) 创建使用默认大小的输入缓冲区的缓冲字符输入流。

特殊的成员方法:

public String readLine() 一次读取一行数据,但是不会读取换行符

package day17.Study;
import java.io.BufferedReader;
import java.io.FileReader;
/*
字符流:(当一个文件使用记事本打开能看懂的时候,就可以使用字符流)
        字符输入流:
            Reader
                - InputStreamReader
                    -FileReader
                - BufferedReader(字符缓冲输入流)
        字符输出流:
            Writer
                - OutputStreamWriter
                    - FileWriter
                - BufferedWriter(字符缓冲输出流)
    字符缓冲输入流(BufferedReader)
        构造方法:
            BufferedReader(Reader in)  创建使用默认大小的输入缓冲区的缓冲字符输入流。
        特殊的成员方法
            public String readLine() 一次读取一行数据,但是不会读取换行符
 */
public class BufferedReaderDemo1 {
    public static void main(String[] args) throws Exception{
        //创建字符缓冲输入流对象
//        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("src/com/day17/data2/b1.txt")));
        BufferedReader br = new BufferedReader(new FileReader("src/com/day17/data2/b1.txt"));
        //一次读取一个字符
//        int i = 0;
//        while((i= br.read())!=-1){
//            System.out.print((char)i);
//        }
//        //一次读取一个字符数组
//        char[] chars = new char[1024];
//        int length = 0;
//        while ((length=br.read(chars))!=-1){
//            String s = new String(chars,0,length);
//            System.out.println(s);
//        }
        //public String readLine() 一次读取一行数据,但是不会读取换行符
//        System.out.println(br.readLine());
//        System.out.println(br.readLine());
//        System.out.println(br.readLine());
//        System.out.print(br.readLine());
//        System.out.print(br.readLine());
        String line = null;
        while((line= br.readLine())!=null){
            System.out.println(line);
        }
        br.close();
    }
}

三、序列化和反序列化(对象的输入输出流)

序列化流:

序列化:将一个对象转换成网络中传输的流

        对象输出流:ObjectOutputStream

反序列化:将网络中的传输的流还原成一个对象

        对象输入流;ObjectInputStream

 创建对象Student

package day18;
import java.io.Serializable;

/*
一个类的对象将来要想实现序列化,必须要实现Serializable接口,该接口中没有任何的方法和常量,被称为标记接口
我们在写完对象后,又修改了类中的内容,再读取还原对象的时候,报错了
        com.shujia.day18.ketang.Student;
        local class incompatible:
        stream classdesc serialVersionUID = 2442942279365203766,
        local class serialVersionUID = 2935475373948736279
2935475373948736279和2442942279365203766这两个值不一样,报错
解决方案:将serialVersionUID写固定,将来谁都不能改,自动生成即可。

    若成员不想被序列化存储,使用java提供的关键字

 */
public class Student implements Serializable {
    private static final long serialVersionUID = -1835923285942095888L;
    private String name;
    private int age;
    private String address;
    private transient String phone;

    public Student() {
    }

    public Student(String name, int age, String address, String phone) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

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

 序列化测试类:

package day18;
import java.io.*;

/*
    序列化流:
        序列化:将一个对象转换成网络中传输的流
            对象输出流:ObjectOutputStream
        反序列化:将网络中的传输的流还原成一个对象
            对象输入流;ObjectInputStream
 */
public class ObjectOutputStreamDemo1 {
    public static void main(String[] args) {
//        write();
        read();
    }
    private static void read() {
        //public ObjectInputStream(InputStream in)
        ObjectInputStream ois = null;
        try {
             ois = new ObjectInputStream(new FileInputStream("src/com/shujia/day18/data/object.txt"));
            Object o = ois.readObject();//new Student("古巨基", 19,"安徽合肥","100");
            Student student = (Student) o;
            System.out.println(student);
        } catch (Exception e) {
           e.printStackTrace();
        }finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private static void write() {
        ObjectOutputStream oos = null;
        try {
            //ObjectOutputStream(OutputStream out) 创建一个写入
            oos = new ObjectOutputStream(new FileOutputStream("src/com/shujia/day18/data/object.txt"));
            //void writeObject(Object obj)将指定的对象写入ObjectOutputStream
            Student s1 = new Student("古巨基", 19,"安徽合肥","100");
            oos.writeObject(s1);
            oos.flush();//刷到文件中

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

四、练习

-- 1、判断D盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件的名称


-- 2、递归遍历目录下指定后缀名的文件名称,输出


-- 3、字节流数据的输入和输出


-- 4、字节缓冲流数据的输入和输出


-- 5、字节流数据的输入和输出


-- 6、复制文本文件


-- 7、复制图片


-- 8、把ArrayList集合中的字符串数据存储到文本文件


-- 9、从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合


-- 10、复制单级文件夹


-- 11、键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件


-- 12、已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
 请编写程序读取数据内容,把数据排序后写入ss.txt中。

五、案例

-- 1、判断D盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件的名称

package com.day16;
/*
判断D盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件的名称
 */


import java.io.File;

public class FileTest1 {
    public static void main(String[] args) {
        File file = new File("E:\\");

        File[] listFiles = file.listFiles();
        if (listFiles!=null){
            for(File file1: listFiles){
                 if(file1.getName().endsWith(".jpg") && file1.isFile()){
                     System.out.println(file1.getName());
                 }else{
                     System.out.println("NO");
                 }
            }
        }
    }
}

-- 2、递归遍历目录下指定后缀名的文件名称,输出

package day16;
//递归遍历目录下指定后缀名的文件名称,输出
import java.io.File;

public class FileTest3 {
    public static void main(String[] args) {
        File file = new File("E:\\bigdata");
        getJPGFile(file);

    }

    public static void getJPGFile(File file){
        if(file!=null){
            File[] listFiles = file.listFiles();
            if (listFiles!=null){
                for(File file1 : listFiles){
                    if(file1.isFile() && file1.getName().endsWith(".txt")){
                        System.out.println(file1.getName());
                    } else if (file1.isDirectory()) {
                        getJPGFile(file1);
                    }
                }
            }
        }
    }
}

-- 3、字节流数据的输入和输出

package day17.Study;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/*
    数据源:src/com/shujia/day17/data1/1.jpg
        读取数据 - 输入流 - 字节流输入流 - InputStream - FileInputStream
    目的地:src/com/shujia/day17/data1/3.jpg
        写数据 - 输出流 - 字节输出流 - OutputStream - FileOutStream
 */
public class CopyFileDemo1 {
    public static void main(String[] args) throws Exception{
        //创建字节的输入流
        FileInputStream fis = new FileInputStream("src/com/day17/data1/1.jpg");
        //创建字节的输出流
        FileOutputStream fos = new FileOutputStream("src/com/day17/data1/3.jpg");
        //方式1:一次读写一个字节
        int i = 0;
        while((i= fis.read()) != -1){
            fos.write(i);
        }
//        //方式2:一次读写一个字节数组
//        byte[] bytes = new byte[1024];
//        int length = 0;
//        while((length = fis.read(bytes))!=-1){
//            fos.write(bytes,0,length);
//        }
        fos.close();
        fis.close();
    }
}

-- 4、字节缓冲流数据的输入和输出

package day17.Study;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFileDemo2 {
    public static void main(String[] args) throws Exception {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\aaa.mp4"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:\\bbb.mp4"));

        byte[] bytes = new byte[4096];
        int length = 0;
        while((length = bis.read(bytes))!=-1){
            bos.write(bytes,0,length);
//            bos.flush();
        }
//        int i = 0;
//        while((i= bis.read())!=-1){
//            bos.write(i);
//        }
        bos.close();
        bis.close();
    }
}

-- 5、字节流数据的输入和输出

package day17.Study;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class CopyFileDemo3 {
    public static void main(String[] args) throws Exception{
        //创建字符输入流对象
        InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\Test.txt"));

        //创建字符输出流对象
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/com/day17/data2/Word.txt"));

        //方式1:一次读写一个字符
        int i = 0;
        while ((i= isr.read())!=-1){
            osw.write(i);
            osw.flush();
        }
        //方式2:一次读写一个字符数组
        char[] chars = new char[1024];
        int length = 0;
        while((length = isr.read(chars))!=-1){
            osw.write(chars,0,length);
            osw.flush();
        }
        //释放资源
        osw.close();
        isr.close();
    }
}

-- 6、复制文本文件

package com.shujia.day17.HomeWork;
import java.io.*;
/*
复制文本文件
*/
public class HomeWork1 {
    public static void main(String[] args) throws Exception{
        long start = System.nanoTime();
        BufferedReader br = new BufferedReader(new FileReader("src/com/day17/data1/11.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("src/com/day17/data1/12.txt"));
        int i = 0;
        while((i = br.read())!=-1){
            bw.write((char)i);
        }
        br.close();
        bw.close();
        long end = System.nanoTime();
        System.out.println("方法1所用时间:" + (end - start)+"\n");
    }
}

-- 7、复制图片

package day17.HomeWork;
import java.io.*;
/*
复制图片
 */
public class HomeWork2 {
    public static void main(String[] args) throws Exception{
        long start = System.nanoTime();
        FileInputStream fis = new FileInputStream("src/com/day17/data1/1.jpg");
        FileOutputStream fos = new FileOutputStream("src/com/day17/data1/2.jpg");
        byte[] bytes = new byte[1024];
        int length = 0;
        while((length= fis.read(bytes))!=-1){
            fos.write(bytes,0,length);
        }
        fis.close();
        fos.close();
        long end = System.nanoTime();
        System.out.println("方法1所用时间:" + (end - start)+"\n");
    }
}

-- 8、把ArrayList集合中的字符串数据存储到文本文件

package day17.HomeWork;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;

/*
把ArrayList集合中的字符串数据存储到文本文件
 */
public class HomeWork3 {
    public static void main(String[] args) throws Exception{
        long start = System.nanoTime();
        ArrayList<String> list = new ArrayList<>();
        BufferedWriter bw = new BufferedWriter(new FileWriter("src/com/day17/data1/31.txt"));
        list.add("黑神话悟空");
        list.add("死亡搁浅");
        list.add("星际战士");

        for(String s:list){
            bw.write(s);
            bw.newLine();
            bw.flush();
        }
        bw.close();
        long end = System.nanoTime();
        System.out.println("方法1所用时间:" + (end - start)+"\n");
    }
}

-- 9、从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合

package day17.HomeWork;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

/*
从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合
 */
public class HomeWork4 {
    public static void main(String[] args) throws Exception{
        long start = System.nanoTime();
        ArrayList<String> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader("src/com/day17/data1/41.txt"));
        char[] chars = new char[1024];
        int length = 0;
        while ((length = br.read(chars))!=-1){
            String s = new String(chars,0,length);
            list.add(s);
        }

        for(String s:list){
            System.out.println(s);
        }
        br.close();
        long end = System.nanoTime();
        System.out.println("方法1所用时间:" + (end - start)+"\n");
    }
}

-- 10、复制单级文件夹

package day17.HomeWork;
import java.io.*;

/*
复制单级文件夹
 */
public class HomeWork5 {
    public static void main(String[] args) throws IOException {
        File srcFolder = new File("D:\\aaa");
        String srcFolderName = srcFolder.getName();
        File destFolder = new File("E:\\",srcFolderName);

        if(!destFolder.exists()){
            destFolder.mkdir();
        }

        File[] srcFiles = srcFolder.listFiles();

        for(File srcFile : srcFiles){
            String srcFileName = srcFile.getName();
            File destFile = new File(destFolder, srcFileName);
            copyFile(srcFile ,destFile);
        }
    }
    private static void copyFile(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));

        byte[] bytes = new byte[1024];
        int length;
        while((length= bis.read(bytes))!=-1){
            bos.write(bytes,0,length);
            bos.flush();
        }
        bos.close();
        bis.close();
    }
}

-- 11、键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件

Student类:

package day17.HomeWork;

public class Student {
    private String name;
    private int chinese;
    private int math;
    private int english;

    public Student() {
    }

    public Student(String name, int chinese, int math, int english) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
        this.english = english;
    }

    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 getSum(){
        return chinese + math + english;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", chinese=" + chinese +
                ", math=" + math +
                ", english=" + english +
                '}';
    }
}

 测试类:

package day17.HomeWork;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
/*
键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
 */
public class HomeWork8 {
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new FileWriter("src/com/day17/data1/81.txt"));
        TreeSet<Student> set = new TreeSet<>(new Comparator<Student  >() {
            @Override
            public int compare(Student o1, Student o2) {
                int i = o2.getSum()- o1.getSum();
                //隐式条件:
                //总分一样,各科的分数不一定一样
                //总分一样,语文成绩不一定一样
                int i2 = (i==0)? o2.getChinese() - o1.getChinese():i;
                //总分,语文成绩一样,数学成绩不一定一样
                int i3 = (i2==0)? o2.getMath() - o1.getMath():i2;
                //各科分数一样,姓名不一定一样
                return (i3==0)? o2.getName().compareTo(o1.getName()):i3;
            }
        });
        Student student;
        for (int i = 1; i <= 5; i++) {
            System.out.println("请输入第 "+i+" 个学生的信息:");
            System.out.print("姓名:");
            String name = sc.next();
            System.out.print("语文成绩:");
            int chinese = sc.nextInt();
            System.out.print("数学成绩:");
            int math = sc.nextInt();
            System.out.print("英语成绩:");
            int english = sc.nextInt();
            //创建一个学生对象,将当前学生的信息进行封装
            student = new Student(name,chinese,math,english);
            //将学生对象添加到集合中
            set.add(student);
        }
        for(Student student1 : set){
            bw.write(student1.toString());
            bw.newLine();
        }
        bw.flush();
        bw.close();
    }
}

-- 12、已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl” 请编写程序读取数据内容,把数据排序后写入ss.txt中。

package day17.HomeWork;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Arrays;

/*
已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
 请编写程序读取数据内容,把数据排序后写入ss.txt中。
    分析:
        1、文件是一个普通文件,打开是可以看懂的,所以采用字符流
        2、速度要求快的话,字符缓冲流
        3、内容只有一行,直接读取一行
        4、先转字符数组
        5、使用Arrays工具类进行排序
 */
public class HomeWork9 {
    public static void main(String[] args) throws Exception{
        //创建字符缓冲输入流读取数据
        BufferedReader br = new BufferedReader(new FileReader("src/com/day17/data1/s.txt"));
        String info = br.readLine();
        char[] chars = info.toCharArray();
        Arrays.sort(chars);
        String s = new String(chars);
        System.out.println(s);
        //创建字符缓冲输出流写入数据
        BufferedWriter bw = new BufferedWriter(new FileWriter("src/com/day17/data1/ss.txt"));
        bw.write(s);
        bw.flush();
        bw.close();
        br.close();
    }
}
  • 22
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值