上好的文件

文件流

文件在程序中是以流的形式来操作的

java程序(内存中) -------------> 输出流 -------------> 文件(磁盘)

java程序(内存中) <------------- 输入流 <------------- 文件(磁盘)

流:数据在数据源和程序之间经历的路径

输入流:数据从数据源(文件)到程序(内存)的路径

输出流:数据从程序(内存)到数据源(文件)的路径

流的分类

  • 操作数据单位不同:字节流,字符流
  • 数据流流向:输入流,输出流
  • 流的角色:节点流,处理流,包装流

都是抽象类

InputStream字节输入流

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

  • BufferedInputStream 缓冲字节输入流
  • ObjectInputStream 对象字节输入流

OutputStream字节输入流

  • FileInputStream 文件输出流
            String filePath = "e:\\a.txt";
            FileOutputStream fileOutputStream = null;
            try {
                //得到 FileOutputStream对象 对象
                //1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
                //2. new FileOutputStream(filePath, true) 创建方式当写入内容是,是追加到文件后面
                fileOutputStream = new FileOutputStream(filePath, true);
                //写入一个字节
                //fileOutputStream.write('H');//
                //写入字符串
                String str = "hsp,world!";
                //str.getBytes() 可以把 字符串-> 字节数组
                //fileOutputStream.write(str.getBytes());
                /*
                write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流
                 */
                fileOutputStream.write(str.getBytes(), 0, 3);
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

节点流

 

针对特定的数据源进行读写,数据源是存放数据的

 功能不是很强大,受限制于数据源

FileReader 和FileWriter文件字符流 

FileReader

    public void readFile01() {
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;
        int data = 0;
        //1. 创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取 使用read, 单个字符读取
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }

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

    /**
     * 字符数组读取文件
     */

    public void readFile02() {
        System.out.println("~~~readFile02 ~~~");
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;

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

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

FileWriter

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

        String filePath = "e:\\note.txt";
        //创建FileWriter对象
        FileWriter fileWriter = null;
        char[] chars = {'a', 'b', 'c'};
        try {
            fileWriter = new FileWriter(filePath);//默认是覆盖写入
//            3) write(int):写入单个字符
            fileWriter.write('H');
//            4) write(char[]):写入指定数组
            fileWriter.write(chars);
//            5) write(char[],off,len):写入指定数组的指定部分
            fileWriter.write("sadfsdf".toCharArray(), 0, 3);
//            6) write(string):写入整个字符串
            fileWriter.write(" dsfsfsdf");
            fileWriter.write("cxk是条狗");
//            7) write(string,off,len):写入字符串的指定部分
            fileWriter.write("绝杀", 0, 2);
            //在数据量大的情况下,可以使用循环操作.


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

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

        assert var2 <= var1;

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

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

        }

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

    }

处理流(包装流)

连接已经存在的流(节点流,处理流)之上,为程序提供更为强大的读写功能,bufferedReader,bufferedWriter

 bufferedReader

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

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

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

         */
        bufferedReader.close();

bufferedWriter类似  原理都是在外面包了一层实现了更加强大的功能

对象流ObjectInputStream ObjectOutputStream 其实也是包装流

将基本数据类型和对象进行序列化和反序列化

序列化:

  1. 保存数据时,保存数据的值和数据类型
  2. 反序列化就是在恢复数据时,恢复数据的值和数据类型
  3. 需要让某个对象支持序列化机制,则必须让其类是可序列化的,实现两个接口之一,serializable externalizable
    public class ObjectInputStream_ {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
    
            //指定反序列化的文件
            String filePath = "e:\\data.dat";
    
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
    
            //读取
            //1. 读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
            //2. 否则会出现异常
    
            System.out.println(ois.readInt());
            System.out.println(ois.readBoolean());
    
            System.out.println(ois.readChar());
            System.out.println(ois.readDouble());
            System.out.println(ois.readUTF());
    
    
            //dog 的编译类型是 Object , dog 的运行类型是 Dog
            Object dog = ois.readObject();
            System.out.println("运行类型=" + dog.getClass());
            System.out.println("dog信息=" + dog);//底层 Object -> Dog
    
            //这里是特别重要的细节:
    
            //1. 如果我们希望调用Dog的方法, 需要向下转型
            //2. 需要我们将Dog类的定义,放在到可以引用的位置
            Dog dog2 = (Dog)dog;
            System.out.println(dog2.getName()); //旺财..
    
            //关闭流, 关闭外层流即可,底层会关闭 FileInputStream 流
            ois.close();
    
    
        }
    
    
    
    public class ObjectOutStream_ {
        public static void main(String[] args) throws Exception {
            //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
            String filePath = "e:\\data.dat";
    
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
    
            //序列化数据到 e:\data.dat
            oos.writeInt(100);// int -> Integer (实现了 Serializable)
            oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable)
            oos.writeChar('a');// char -> Character (实现了 Serializable)
            oos.writeDouble(9.5);// double -> Double (实现了 Serializable)
            oos.writeUTF("cxk也配当人?");//String
            //保存一个dog对象
            oos.writeObject(new Dog("旺财", 10, "aa", "bb"));
            oos.close();
            System.out.println("数据保存完毕(序列化形式)");
    
    
        }
    }

    注意事项和细节说明

  •      读写顺序要一致
  • 要求实现序列化或反序列化对象,需要实现Serializable
  • 序列化的类中建议添加SerialVersionUID 为了提高版本兼容性
  • 序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
  • 序列化对象时,要求里面属性的类型也需要实现序列化接口
  • 序列化具备可继承性,也就是如果某类已经实现了序列化,则他的所有子类也已经默认实现了序列化   

标准输入输出流

 System.in 标准输入    类型时InputStream  默认设备键盘

 System.out 标准输出  类型时PrintStream  默认设备显示器

转换流

InputStreamReader   OutputStreamWriter  针对文件乱码问题

 

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

        String filePath = "e:\\a.txt";
        //1. 把 FileInputStream 转成 InputStreamReader
        //2. 指定编码 gbk
        //InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
        //3. 把 InputStreamReader 传入 BufferedReader
        //BufferedReader 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();

    }
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "e:\\aaa.txt";
        String charSet = "utf-8";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
        osw.write("hi, cxk也配当人?");
        osw.close();
        System.out.println("按照 " + charSet + " 保存文件成功~");

打印流

PrintStream PrintWriter 打印流只有输出流 没有输入流

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

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

         */
        out.print("john, hello");
        //因为print底层使用的是write , 所以我们可以直接调用write进行打印/输出
        out.write("cxk是条狗".getBytes());
        out.close();

        //我们可以去修改打印流输出的位置/设备
        //1. 输出修改成到 "e:\\f1.txt"
        //2. "cxk是狗" 就会输出到 e:\f1.txt
        //3. public static void setOut(PrintStream out) {
        //        checkIO();
        //        setOut0(out); // native 方法,修改了out
        //   }
        System.setOut(new PrintStream("e:\\f1.txt"));
        System.out.println("cxk是狗");
public class PrintWriter_ {
    public static void main(String[] args) throws IOException {

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

    }
}

Properties类

专门用于读写配置文件的集合类

配置文件格式  键=值  不需要有空格 不需要引号 默认为String

 

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

        //1. 创建Properties 对象
        Properties properties = new Properties();
        //2. 加载指定配置文件
        properties.load(new FileReader("src\\mysql.properties"));
        //3. 把k-v显示控制台
        properties.list(System.out);
        //4. 根据key 获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名=" + user);
        System.out.println("密码是=" + pwd);



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

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

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

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

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值