JavaIO流 笔记

IO流

一、创建文件


1. 方式一 new File(String pathname)

public void create02() throws IOException {
        File file = new File("e:\\", "news2.txt");
        file.createNewFile();

        System.out.println("文件创建成功!");
    }

2. 方式二 new File(File parent,String child) 根据父目录文件+子路径构建

 public void create03() throws IOException {
        String parent = "e:\\";
        String filePath = "news3.txt";

        File file = new File(parent, filePath);
        file.createNewFile();
   }

3. 方式三 new File(String parent,String child) 根据父目录+子路径构建

 public void create03() throws IOException {
        String parent = "e:\\";
        String filePath = "news3.txt";

        File file = new File(parent, filePath);
        file.createNewFile();
   }

二、获取文件信息


public class FileInformation {
    //获取文件信息
    @Test
    public void info(){
        //先创建文件对象
        File file = new File("e:\\news3.txt");

        //调用相应的方法,得到对应信息
        System.out.println("文件名字:"+ file.getName());
        System.out.println("文件绝对路径:"+file.getAbsolutePath());
        System.out.println("得到文件父目录:"+file.getParentFile());
        System.out.println("文件大小(字节):"+file.length());
        System.out.println("文件是否存在:"+file.exists());
        System.out.println("是不是一个文件:"+file.isFile());
        System.out.println("是不是一个目录:"+file.isDirectory());
}

三、目录操作


1. 判断文件 e:\\new3.txt 是否存在,如果存在就删除

在java中,目录也被当作文件

    @Test
    public void m1(){

        String filePath = "e:\\news3.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("该文件不存在...");
        }

    }

2. 判断目录 e:\demo02 是否存在,如果存在就删除

    @Test
    public void m2(){
        String filePath = "e:\\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("该目录不存在...");
        }
    }

3. 判断目录 e:\\demo\\a\\b\\c 是否存在,如果存在就提示已存在,否则就创建

注意:创建一级目录用mkdir,多级目录操作用mkdirs

    @Test
    public void m3(){
        String directoryPath = "e:\\demo\\a\\b\\c";
        File file = new File(directoryPath);
        if(file.exists()){
            System.out.println(directoryPath + "存在...");
        }else{
           if (file.mkdirs()){
               System.out.println(directoryPath +"创建成功!");
           }else {
               System.out.println(directoryPath +"创建失败!");
           }
        }
    }

四、IO流原理及流的分类


原理:

输入input:

读取外部数据(磁盘,光盘等存储设备数据)到程序(内存)中

输出output:

将程序(内存)数据输出到磁盘、光盘等存储设备中

流的分类:

  • 操作数据单位不同:
    • 字节流(8bit)如二进制
    • 字符流(按字符)如文本文件
  • 数据流的流向不同:
    • 输入流
    • 输出流
  • 流的角色的不同分为:
    • 节点流
    • 处理流/包装流

这四个都是抽象类

五、InputStream 字节输入流


四个子类

  • FileInputStream
  • ObjetInputStream
  • FileterInputStream
  • BufferedInputStream

1.FileInputStream


read()单个字节读取,效率比较低

//读取文件  
@Test
public void readFile01(){
    
    String filePath = "e:\\hello.txt";
    int read = 0;
    FileInputStream fileInputStream = null;

    try {

        //创建一个FileInputStream 对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);

        //如果返回-1,表示读取完毕
        while((read = fileInputStream.read())!= -1){
            System.out.print((char)read);//转成char显示
        }

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

read(byte[] b)一次读取多个字节

@Test
public void readFile02() {

    String filePath = "e:\\hello.txt";
    int readLen = 0;

    byte[] buf = new byte[8];//一次读取8个字节
    FileInputStream fileInputStream = null;

    try {

        //创建一个FileInputStream 对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);

        //如果返回-1,表示读取完毕
        //如果读取正常,返回实际读取的字节数
        while ((readLen = fileInputStream.read(buf)) != -1) {
            System.out.print(new String(buf, 0, readLen));//转成String显示
        }

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

六、OuputStream 字节输出流


1.FileOutputStream

将数据写到文件中,如果文件不存在,则自动创建文件

注意点

1.new FileOutputStream(filePath); 
创建方式,当写入内容时,会覆盖原来的内容
2.new FileOutputStream(filePath,true); 
创建方式,当写入内容时,是追加到文件内容后面
3.char会自动转换为int

write()
写入一个字节
写入字符串
自定义起始位置及长度
@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');//char会自动转换为int
        //写入字符串
        String str = "hlo,world";
        //str.getBytes() 可以把 字符串  转化为 字节数组
        //fileOutputStream.write(str.getBytes());
        fileOutputStream.write(str.getBytes(),0,5);

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

文件拷贝

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

        //文件拷贝,将d:\\ykh.jpg 拷贝到 e:\\
        //1.创建文件的输入流,
        //2,创建文件的输出流,

        String srcfilePath = "d:\\ykh.jpeg";
        String destFilePath = "e:\\ykh.jpeg";

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(srcfilePath);
            fileOutputStream = new FileOutputStream(destFilePath);

            //定义一个字节数组,提高读取效率
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf))!= -1){
                //读取到后,就写入到文件 通过fileOutputStream
                //一边读一边写
                fileOutputStream.write(buf,0,readLen);//一定要使用这个方法
            }
            System.out.println("拷贝成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
                if (fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

七、FileReader


使用read,单个字符读取

public static void main(String[] args) {

    String filePath = "e:\\story.txt";
    FileReader fileReader = null;
    int data = 0;

    try {
        //1.创建FileReader对象
        fileReader = new FileReader(filePath);
        //循环读取,使用read,单个字符读取
        while((data = fileReader.read()) != -1){
            System.out.print((char)data);
        }

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

使用read(buf),返回实际读取字符数

@Test
public void read02(){
    String filePath = "e:\\story.txt";

    FileReader fileReader = null;
    int readLen = 0;
    char[] buf = new char[8];

    try {
        //1.创建FileReader对象
        fileReader = new FileReader(filePath);
        //循环读取,使用read(buf),返回实际读取字符数
        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();
        }
    }
}

八、FileWriter


  • writer(int):写入单个字符
  • writer(char[]):写入指定数组
  • writer(char[],off,len):写入指定数组的指定部分
  • writer(string) :写入字符串
  • writer(string,off,len):写入字符串的指定部分

注意:

对于FileWriter,一定要关闭流,或者flush才能真正把数据写到文件中

 @Test
    public void writer01(){

        String filePath = "e:\\noto.txt";
        FileWriter fileWriter = null;

        try {
            //创建FileWriter对象
            fileWriter = new FileWriter(filePath);

            //1.writer(int):写入单个字符
//            fileWriter.write('H');

            //2.writer(char[]):写入指定数组
            char[] chars = {'a','b','c'};
//            fileWriter.write(chars);

            //3.writer(char[],off,len):写入指定数组的指定部分
//            fileWriter.write("颜奈斯啦啦啦".toCharArray(),0,3);

            //writer(string) :写入字符串
//            fileWriter.write("颜奈斯");

            //writer(string,off,len):写入字符串的指定部分
            fileWriter.write("颜奈斯石达开",0,2);

            //在数据量大的情况下,可以使用循环操作
            
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

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

            //对于FileWriter,一定要关闭流,或者flush才能真正把数据写到文件中
        }

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

九、节点流和处理流


数据源:存放数据的地方

节点流:

从一个特定的数据源读取数据,固定的,有局限性,如FileReader,FileWriter


处理流(包装流):

连接在已存在的流(节点流或处理流)之上,为程序提供更强大的读写功能,更加灵活,如BufferedWriter,BufferedReader


一、字符处理流

1.BufferedReader


  • readLine()
    • 按行读取,返回一个字符串
    • 当返回为null时,文件读取完毕
  • 关闭流
    • 这里只需要关闭 bufferedReader ,因为底层会自动去关闭节点流FileReader
public class BufferReader_ {
    public static void main(String[] args) throws Exception {
        
        String filePath = "e:\\Test02Test.java";

        //创建BufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));

        //读取
        String line;//按行读取,效率高

        //readLine() 按行读取,返回一个字符串
        //当返回为null时,文件读取完毕
        while((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }
        //关闭流,这里只需要关闭 bufferedReader ,因为底层会自动去关闭节点流FileReader
        bufferedReader.close();
        
    }
}

2.BufferedWriter


  • 插入一个换行
    • bufferedWriter.newLine();
public class BufferedWriter_ {
    public static void main(String[] args) throws IOException {

        String filePath = "e:\\ok.txt";

        //创建  BufferedWriter
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
        bufferedWriter.write("hello4,颜奈斯!");
        //插入一个换行
        bufferedWriter.newLine();
        bufferedWriter.write("hello5,颜奈斯!");
        bufferedWriter.newLine();
        bufferedWriter.write("hello6,颜奈斯!");

        //关闭
        bufferedWriter.close();
    }
}

3.Buffered拷贝


不要去操作二进制文件,可能会造成文件损坏

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

        String srcFilePath = "e:\\ok.txt";
        String destFilePath = "e:\\thank.txt";

        BufferedReader br = null;
        BufferedWriter bw = null;
        String line;
        try {

            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));

            while((line = br.readLine() )!= null){
                //每读取一行就写入
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (br != null){
                    br.close();
                }
                if(bw != null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

二、字节处理流


1.Buffer拷贝

可操作字节也可操作字符

public class BufferedCopy02 {

    public static void main(String[] args) {

        String srcFilePath = "e:\\原神 2022-06-16 14-28-39.mp4";
        String destFilePath = "e:\\lisa.mp4";

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

            //循环读取文件,并写入到 destFilePath
            byte[] buf = new byte[1024];
            int readLen = 0;

            while ((readLen = bis.read(buf))!= -1){
                bos.write(buf,0,readLen);
            }

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

三、对象处理流


  • 序列化:
    • 保存值和数据类型
  • 反序列化:
    • 恢复数据的值和数据类型

如果需要序列化某个类的对象,实现Serializable接口

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

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

1.ObjectOutputStream

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

        //序列化后,保存的文件格式,不是纯文本,而是按照他的格式保存
        String filePath = "e:\\data.dat";

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

        //序列化数据到:e:\\data.dat
        oos.write(100);//int -> Interger (实现了  Serializable)
        oos.writeBoolean(true);//boolean ->Boolean (实现了  Serializable)
        oos.writeChar('a');//char ->Character (实现了  Serializable)
        oos.writeDouble(9.5);//double ->Double (实现了  Serializable)
        oos.writeUTF("颜奈斯!");//String

        //保存一个对象
        oos.writeObject(new Dog("小王",12));

        oos.close();
        System.out.println("数据保存完毕(序列化形式)");

    }
}

//如果需要序列化某个类的对象,实现Serializable接口
class Dog implements Serializable {
    private String name;
    private int age;

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

2.ObjectInputStream


读取(反序列化)的顺序需要和保存数据(序列化)的顺序一致,否则异常

public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

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

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

        //读取
        //读取(反序列化)的顺序需要和保存数据(序列化)的顺序一致,否则异常
        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());
        Object dog = ois.readObject();
        System.out.println("运行类型="+ dog.getClass());
        System.out.println("dog信息="+ dog);//底层 Object -> Dog

        ois.close();

    }
}

四、标准输入输出流


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

        //System.in 编译类型 InputStream
        //System.in 运行类型 BufferedInputStream
        //表示的是标准输入 键盘
        System.out.println(System.in.getClass());

        //System.out 编译类型 PrintStream
        //System.out 运行类型 PrintStream
        //表示标准输出 显示器
        System.out.println(System.out.getClass());

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

五、转换流


问题:如果字符编码不一样,则会出现乱码情况

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 line = br.readLine();
        System.out.println(line);
        br.close();
    }
}

1.InputStreamReader

字节转换成字符流

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

        String filePath = "e:\\a.txt";
        //1.new FileInputStream 转成 InputStreamReader
        //2.指定编码,GBK
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");

        //3.把 InputStreamReader 传入 BufferedReader
        BufferedReader br = new BufferedReader(isr);

        //简化代码2和3
//        BufferedReader br = new BufferedReader(new InputStreamReader(
//                                                    new FileInputStream(filePath), "gbk"));

        //4.读取
        String s = br.readLine();
        System.out.println("读取:"+s);

        //5.关闭
        br.close();

    }
}

2.OutputStreamWriter

字节转换成字符流

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

        String filePath = "e:\\aa.txt";
        //给定编码方式
        String charSet = "UTF-8";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);

        osw.write("颜奈斯");
        osw.close();

    }
}

六、打印流


打印流只有输出流,没有输出流

1.PrintStream


  • 默认情况下打印
    • PrintStream 输出数据的位置是 标准输出,即显示器
  • 修改打印流输出的位置/设备
    • 输出修改成e:\f1.txt
    • “hello,how are you!”就会输出到文本
        System.setOut(new PrintStream("e:\\f1.txt"));
        System.out.println("hello,how are you!");

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

        PrintStream out = System.out;
        //默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
        out.println("颜奈斯!");

        out.write("颜奈斯!!!".getBytes());
        out.close();

        //我们也可以去修改打印流输出的位置/设备
        //1.输出修改成e:\f1.txt
        //2.“hello,how are you!”就会输出到文本
        System.setOut(new PrintStream("e:\\f1.txt"));
        System.out.println("hello,how are you!");
    }
}

2.PrintWriter


public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
        
        //System.out默认打印位置
        //PrintWriter printWriter = new PrintWriter(System.out);

        //改变打印位置
        PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
        printWriter.println("北京你好");
        //一定要有close,真正写数据的
        printWriter.close();
    }
}

十、Properties类


主要方法:

注意:

使用Properties 类来读取 mysql.properties 文件

public class Properties01 {
    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"));

        //3.把key-value显示到控制台
        properties.list(System.out);

        //4.根据key获取对应的value
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println(user);
        System.out.println(pwd);

    }
}

使用Properties类创建配置文件,修改配置文件内容

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

        Properties properties = new Properties();

        //创建
        //setProperty()
        // 如果该文件没有key,就是创建,有key就是修改
        properties.setProperty("charset","utf-8");
        properties.setProperty("user","颜奈斯");
        properties.setProperty("pwd","123456");

        //将key-value 存储文件中即可
        properties.store(new FileOutputStream("src\\mysql2.properties"),null);//null是配置文件中的注释

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值