IO流

IO流

创建文件

package io.lesson;

import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;

import java.io.File;
import java.io.IOException;
//创建文件的三种方法
public class FileCreate {
    public static void main(String[] args) {
        FileCreate fc1 = new FileCreate();
        FileCreate fc2 = new FileCreate();
        FileCreate fc3 = new FileCreate();
        fc1.create01();
        fc2.create02();
        fc1.create03();
    }
    //方式一:new File(String Pathname)
    public void create01(){
        String filePath = "d:\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("第一个文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式二:new File(File parent,String child)//根据父目录文件+子路径构建
    public void create02(){
        File parentFile = new File("d:\\");
        String fileName = "news2.txt";
        File file = new File(parentFile, fileName);
        try {
            file.createNewFile();
            System.out.println("第二个文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式三:new File(String parent,String child)//根据父目录文件+子路径构建
    public void create03(){
        String parentfile = "d:\\";
        String fileName = "news3.txt";
        File file = new File(parentfile, fileName);
        try {
            file.createNewFile();
            System.out.println("第三个文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

获取文件信息

  1. 获取文件相关的信息,如:

​ getName、getAbsolutePath、getParent、length、isFile、isDictionary······

package io.lesson;

import java.io.File;

public class Flieinformation {
    public static void main(String[] args) {
        Flieinformation ff = new Flieinformation();
        ff.info();
    }
    public void info(){
        File file = new File("d:\\end");
        System.out.println("文件名字="+file.getName());
        System.out.println("文件大小="+file.length());
        System.out.println("绝对路径="+file.getAbsolutePath());
        System.out.println("文件父级目录="+file.getParent());
        System.out.println("文件是否存在="+file.exists());
        System.out.println("是不是一个文件="+file.isFile());
        System.out.println("是不是一个目录="+file.isDirectory());
    }
}
  1. 常用的文件操作

    目录的操作和文件删除

    mkdir创建一级目录,mkdirs创建多级目录,delete删除空目录或文件

    mkdir和mkdirs都是布尔值

package io.lesson;

import org.junit.Test;

import java.io.File;

public class Directory_ {
    public static void main(String[] args) {
        Directory_ d1 = new Directory_();
        Directory_ d2 = new Directory_();
        Directory_ d3 = new Directory_();
        d1.m1();
        d2.m2();
        d1.m3();
    }
    //判断D:\\news1.txt文件是否存在,存在就删除
    public void m1(){
        String filePath = "d:\\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编程中,目录也被当做文件
    public void m2(){
        String directoryPath = "d:\\demo02";
        File file = new File(directoryPath);
        if(file.exists()){
            if (file.delete()){
                System.out.println(directoryPath+"删除成功");
            }
            else{
                System.out.println(directoryPath+"删除失败");
            }
        }
        else {
            System.out.println("该目录不存在!");
        }
    }

    //判断D:\\demo\\a\\b\\c是否存在,存在则提示存在,不存在则创建
    public void m3(){
        String directoryPath = "D:\\demo\\a\\b\\c";
        File file = new File(directoryPath);
        if(file.exists()){
            System.out.println("该目录已存在!");
        }
        else {
            if(file.mkdirs()){
                System.out.println("该目录创建成功!");
            }
            else {
                System.out.println("该目录创建失败!");
            }
        }
    }
}

IO流原理以及分类

  1. IO是input和output的缩写,在java程序中,对数据的操作是以**流(stream)**的方式进行

  2. java.io包下提供了各种“流”类和接口,用来获取不同种类的数据,并通过方法输入输出数据

  3. 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中

    输出output:将程序中的数据输出到磁盘、光盘等存储设备中

  4. 流的分类

    • 按操作数据单位分为:字节流和字符流
    • 按数据流向分:输入流,输出流
    • 按流的角色不同可分为:节点流和处理流

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qgG0uv0V-1636982156374)(D:\QQ图片20211111195807.png)]

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b5d0mf4R-1636982156376)(D:\QQ图片20211111195829.png)]

  5. (抽象基类)字节流字符流
    输入流InputStreamReader
    输出流OutputStreamWriter

    以上四个都是抽象类,Java的IO流共涉及40多个类,都很规则,都是他们四个抽象类的子类,子类名称都已父类名作后缀

InputStream和OutputStream常用子类

  1. FileInputStream:字节输入流
package io.inputstream_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;

public class FileInputStream_ {
    public static void main(String[] args) {
        FileInputStream_ fis1 = new FileInputStream_();
        fis1.readFile01();
        FileInputStream_ fis2 = new FileInputStream_();
        fis2.readFile02();
    }

    public void readFile01(){
        String filePath = "d:\\news2.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建fileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            while ((readData = fileInputStream.read()) != -1){
                System.out.print((char)readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileInputStream.close();
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //使用read(byte[] b)读取文件,提高效率
    public void readFile02(){
        String filePath = "d:\\news2.txt";
        //字节数组
        byte[] buf = new byte[8];
        int readLen = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建fileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            while ((readLen = fileInputStream.read(buf)) != -1){
                System.out.print(new String(buf,0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileInputStream.close();
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. FileOutputStream:字节输出流
package io.outputstream_;

import sun.security.util.Length;

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

public class FileOutputStream01 {
    public static void main(String[] args) {
        FileOutputStream01 fos = new FileOutputStream01();
        fos.writeFile();
    }
    public void writeFile(){
        String filePath = "d:\\a.txt";
        FileOutputStream fileOutputStream = null;
        try {
            //创建FileOutputStream对象
            //说明,创建方式是new FileOutputStream(filePath)时,输入的内容会覆盖原来内容
            //如果是new FileOutputStream(filePath,true),则不会覆盖
            fileOutputStream = new FileOutputStream(filePath);
            String str = "Hello,World!";
            //1.写入一个字符
            //fileOutputStream.write('H');
            //2.写入字符串
            //fileOutputStream.write(str.getBytes());
            //写入字符串的另一种方法
            //write(str.getBytes(), int off,int len);从第off个开始输出,输出len个
            fileOutputStream.write(str.getBytes(), 0, 12);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 文件拷贝:FileCopy
package io.outputstream_;



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

public class FileCopy {
    public static void main(String[] args) {
        String srcFilePath = "d:\\zhengjianzhao.jpg";
        String destFilePath = "d:\\zhengjianzhao2.jpg";
        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            //创建文件的输入流,将文件读到程序
            //创建文件的输出流,将读到的数据文件写到指定的文件中
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);
            //定义一个字节数组,提高读取效率
            byte[] bytes = new byte[1024];
            int readDate = 0;
            while ((readDate = fileInputStream.read(bytes)) != -1){
                fileOutputStream.write(bytes);
            }
            System.out.println("拷贝成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  1. FileReader:读取文件
package io.reader_;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReader_ {
    public static void main(String[] args) {
        FileReader_ fr = new FileReader_();
        fr.readFile01();
        FileReader_ fr2 = new FileReader_();
        fr.readFile02();
    }
//单字符读取文件
    public void readFile01(){
        String filePath = "d:\\news2.txt";
        int data = 0;
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            while ((data = fileReader.read()) != -1){
                System.out.print((char)data);
            }
            System.out.println("\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//字符串形式读取文件
    public void readFile02(){
        String filePath = "d:\\news2.txt";
        int readLen = 0;
        char[] buf = new char[8];
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            while ((readLen = fileReader.read(buf)) != -1){
                System.out.print(new String(buf,0,readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  1. FileWriter:写入文件

    FileWriter使用后必须关闭或刷新,否则写入不到指定文件

package io.writer_;

import java.io.FileWriter;
import java.io.IOException;


public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "d:\\news3.txt";
        FileWriter fileWriter = null;
        char[] chars = {'a','b','c'};
        try {
            fileWriter = new FileWriter(filePath);
            //写入的五种方法
            //write(char[]):写入单个字符
            fileWriter.write('H');
            //write(char[]):写入指定数组
            fileWriter.write(chars);
            //write(char[],off,len):写入指定数组的指定部分
            fileWriter.write("曾成进牛逼".toCharArray(),0,3);
            //write(string):写入整个字符串
            fileWriter.write("黄格燕我爱你");
            //write(string,off,len):写入字符串的指定部分
            fileWriter.write("黄格燕你傻逼",2,4);
            //在数据量大的情况下,可以使用循环操作
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  1. 节点流和处理流
    • 节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter
    • 处理流(包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如BufferedReader、BufferedWriter
    • 节点流和处理流的区别和联系
      • 节点流是底层流/低级流,直接跟数据源相接
      • 处理流(包装节点流),既可以消除不同节点的实现差异,也可以提供更方便的方法来完成输入输出。
      • 处理流对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连
    • 处理流的功能主要体现在以下两方面
      • 性能的提高:主要以增加缓冲的方式来提高输入输出的效率
      • 操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便
    • BufferedReader
package io.reader_;

import java.io.BufferedReader;
import java.io.FileReader;

public class BufferedReader_ {
    public static void main(String[] args) throws Exception {
        String filePath = "d:\\news3.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        String line;//按行读取,效率高
        //bufferedReader.readLine()是按行读取文件
        //当返回值为null时,表示文件已经读完
        while ((line = bufferedReader.readLine())!= null){
            System.out.println(line);
        }
        //只需要关闭bufferedReader,因为底层会自动去关闭节点流
        bufferedReader.close();
    }
}
    • BufferedWriter
package io.writer_;

import java.io.BufferedWriter;
import java.io.FileWriter;

public class BufferedWriter_ {
    public static void main(String[] args) throws Exception{
        String filePath = "d:\\news2.txt";
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
        bufferedWriter.write("你好,韩顺平");
        bufferedWriter.newLine();
        bufferedWriter.write("你好,韩顺平");
        bufferedWriter.newLine();
        bufferedWriter.write("你好,韩顺平");
        //关闭流
        bufferedWriter.close();
    }
}
    • BufferedCopy
package io.reader_;

import java.io.*;

public class BufferedCopy_ {
    public static void main(String[] args) {
        String srcPath = "d:\\news2.txt";
        String dataPath = "d:\\news4.txt";
        String line;
        //BufferedReader和BufferedWriter是安装字符操作
        //别去操作二进制文件如:视频,音频,doc,pdf等等,可能会造成文件损坏
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(srcPath));
            bw = new BufferedWriter(new FileWriter(dataPath,true));
            while ((line = br.readLine()) != null){
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(br != null) {
                br.close();
            }
            if(bw != null) {
                bw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • BufferedInputStream和BufferedOutputStream:
package io.outputstream_;

import java.io.*;

public class BufferedCopy02 {
    public static void main(String[] args) {
        String srcPath = "d:\\zhengjianzhao.jpg";
        String detePath = "d:\\zhengjianzhao3.jpg";
        //BufferedInputStream和BufferedOutputStream可以操作二进制文本文件
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        byte[] buf = new byte[1024];
        int len = 0;
        try {
            bis = new BufferedInputStream(new FileInputStream(srcPath));
            bos = new BufferedOutputStream(new FileOutputStream(detePath));
            while ((len = bis.read(buf)) != -1){
                bos.write(buf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 对象流:ObjectInputStream和ObjectOutputStream
    • 序列化就是在保存数据时,保存数据的值和数据类型
    • 反序列化就是在恢复数据时,恢复数据类型和数据的值
    • 为了让某个对象支持序列化机制,则必须让其类是可序列化的,则该类必须实现如下两个接口之一:
      • Serializable:这是一个标记接口,没有方法(推荐使用)
      • Externalizable:该接口有方法需要实际
一:
package io.outputstream_;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class ObjectOutputStream_ {
    public static void main(String[] args) throws Exception{
        //序列化后,保存的文件格式,不是存文本,这里的.txt没影响,而是按照他自己的格式来保存
        String filePath = "d:\\news5.txt";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
        oos.writeInt(100);
        oos.writeBoolean(true);
        oos.writeChar('z');
        oos.writeUTF("黄格燕");
        oos.writeObject(new Dog("旺财",10));
        oos.close();
        System.out.println("数据序列化保存完毕");
    }
}


二:
package io.outputstream_;

import java.io.Serializable;

//如果要序列化某个类的对象,需要实现Serializable
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;
    }
}



三:
package io.inputstream_;



import io.outputstream_.Dog;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException,ClassNotFoundException{
        String filePath = "d:\\news5.txt";
        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.readUTF());
        //dog的编译类型是Object,运行类型是Dog
        Object dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println("dog信息=" + dog);

        //如果我们希望调用Dog方法,需要向下转型
        //如果我们将Dog类定义,拷贝到可以引用的位置
        Dog dog2 = (Dog)dog;
        System.out.println(dog2.getName());

        ois.close();
    }
}
  • 对象处理流使用细节
    • 读写顺序要一致
    • 要求序列化对象和反序列化对象,需要实现Serializable
    • 序列化的类中建议添加Serializable,为了提高版本兼容性
    • 序列化对象时,默认将里面所有属性都序列化,但除了static和transient修饰的成员
    • 序列化对象时,要求里面属性的类型也需要实现序列化接口
    • 序列化具备可继承性,也就是如果某类实现了序列化,则它的所有子类也默认实现了序列化
  • 标准输入输出流
    • System.in 标准输入流 类型:InputStream 默认设备:键盘
    • System.out 标准输出流 类型:OutputStream 默认设备:显示屏
  • 转换流:InputStreamReader和OutputStreamWriter
    • 它们可以把字节流转换为字符流
    • 默认情况下,读取文件是按照"utf-8"的形式
package io.transformation;

import sun.nio.cs.ext.GBK;

import java.io.*;

public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\news2.txt";
        //把FileInputStream转换成InputStreamReader
        //指定编码gbk,因为在文件news2中,我设成了gbk模式
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath),"gbk");
        //把InputStreamReader传入BufferedReader
        BufferedReader br = new BufferedReader(isr);
        String s = br.readLine();
        System.out.println(s);

        br.close();
    }
}





package io.transformation;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\news6.txt";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
        osw.write("hello呀,大家");
        osw.close();
    }
}

  • 打印流PrintStream和PrintWriter(只有输出流,没有输入流)
package io.transformation;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\news6.txt";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
        osw.write("hello呀,大家");
        osw.close();
    }
}

package io.printstream;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
        //PrintWriter pw = new PrintWriter(System.out);
        PrintWriter pw = new PrintWriter(new FileWriter("d:\\news8.txt"));
        pw.println("你好,黄格燕");
        pw.close();
    }
}


  • Properties类(专门用于读写配置文件的集合类)

    • 配置文件的格式

      • 键=值

        键=值

      • 键值对不需要有空格,值不需要用引号括起来。默认类型是String

    • Properties的常见方法

      • load:加载配置文件的键值对到Preperties对象
      • list:将数据显示到指定设备
      • getproperty(key):根据获取键值
      • setProperty(key,value):设置键值对到Properties对象
      • store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码
      • http://tool.chinaz.com/tools/unicode.aspx unicode码查询工具
package io.properties;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class Properties02 {
    public static void main(String[] args) throws IOException {
        //使用Properties类来读取mysql.properties文件

        //创建Properties对象
        Properties properties = new Properties();
        //加载指定配置文件
        properties.load(new FileReader("C:\\Users\\ZCJ\\IdeaProjects\\JavaSESE\\Test\\src\\mysql.properties"));
        //吧k-v显示在控制台
        properties.list(System.out);
        //根据key值获取对应的值
        String user = properties.getProperty("user");
        String psw = properties.getProperty("psw");
        System.out.println("用户名是:" + user);
        System.out.println("密码是:" + psw);
    }
}


package io.properties;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class Properties03 {
    public static void main(String[] args) throws IOException {
        //使用properties类 来创建配置文件,修改配置文件内容
        Properties properties = new Properties();
        properties.setProperty("charset","utf-8");
        properties.setProperty("user","汤姆");
        properties.setProperty("psw","28545");

        //将k-v  存储文件中即可
        properties.store(new FileWriter("C:\\Users\\ZCJ\\IdeaProjects\\JavaSESE\\Test\\src\\mysql2.properties"),null);
        System.out.println("保存配置文件成功!");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值