java-IO流

IO流

在这里插入图片描述

字节流

字节输出流

package iotext;

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

/*
    java.io.OutputStream  这个抽象类是表示字节输出流的所有类的超类。

    定义了一些子类共性的方法
        void close()                 关闭此输出流并释放与此流相关联的任何系统资源。
        void flush()                 刷新此输出流并强制任何缓冲的输出字节被写出。
        void write(byte[] b)         将 b.length字节从指定的字节数组写入此输出流。
        void write(byte[] b, int off, int len) 从指定的字节数组写入 len个字节,从偏移 off开始输出到此输出流。
        abstract void write(int b)    将指定的字节写入此输出流。

        java.io.FileOutputStream extends OutputStream
        FileOutputStream,文件字节输出流
        把内存中的数据写到硬盘的文件中

        构造方法
            FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。
            FileOutputStream(File file)   创建文件输出流以写入由指定的 File对象表示的文件。
            参数,写入数据的目的
                String name,目的地是一个文件的路径
                File file,目的地是一个文件
       构造方法的作用
            1.创建一个FileOutputStream对象
            2.会根据构造方法中的文件、文件路径创建于一个空的文件
            3.会把FileOutputStream指向对应的文件

      写入数据的原理
         java程序-->JVM(java虚拟机)-->OS(操作系统)-->OS调用写数据的方法-->把数据写入文件中
      字节输出流使用步骤(重要)
        1.创建FileOutputStream对象,构造方法中传入写入的目的地
        2.调用FileOutputStream对象中的方法write,把数据写入文件中
        3.释放资源(流的使用会占用一部分资源,我们在使用结束后需要释放资源,提高程序效率)

*/
public class Outputstream {
    public static void main(String[] args) throws IOException {
        //1.创建FileOutputStream对象,构造方法中传入写入的目的地
        FileOutputStream fos = new FileOutputStream("F:\\makedown\\ceshi\\a.txt");
        //2.调用FileOutputStream对象中的方法write,把数据写入文件中
        fos.write(97);
        // 3.释放资源
        fos.close();
    }
}

在这里插入图片描述

一次写多个字节
package iotext;

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

/*
    一次写多个字节的方法
        void write(byte[] b)         将 b.length字节从指定的字节数组写入此输出流。
        void write(byte[] b, int off, int len) 从指定的字节数组写入 len个字节,从偏移 off开始输出到此输出流。
*/
public class Demo02 {
    public static void main(String[] args) throws IOException {
        //创建OutputStream对象,其构造方法中传递路径
        FileOutputStream fos = new FileOutputStream("F:\\makedown\\ceshi\\b.txt");
        //使用相应的方法写入
        //在文件中写入100
        fos.write(49);
        fos.write(48);
        fos.write(48);

        /*
        void write(byte[] b)         将 b.length字节从指定的字节数组写入此输出流。
            如果第一个字节是正数(0-127),那么显示会查询ASCII码表
            如果第一个字节是负数,那么显示会与第二个字节显示为一个中文字符,选择查询系统码表
        */
        byte[] by={49,48,48};
        fos.write(by);

        /*
         void write(byte[] b, int off, int len) 从指定的字节数组写入 len个字节,从偏移 off开始输出到此输出流。
        */
        byte[] byu={49,49,49,49,49,48,48};
        fos.write(byu,4,3);

       /*
       写入字符的方法,使用String类中的方法把字符转换为字节
            byte[] getBytes(String charsetName) 使用命名的字符集将此 String编码为字节序列,将结果存储到新的字节数组中。
       */
        String s="Hello World";
        byte[] bytes = s.getBytes();
        fos.write(bytes);

        //关闭文件
        fos.close();
    }
}
数据的追加写换行写
package iotext;

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

/*
    追加写(续写),使用两个参数的构造方法
    FileOutputStream(String name, boolean append)    创建文件输出流以指定的名称写入文件。
    FileOutputStream(File file, boolean append)      创建文件输出流以写入由指定的 File对象表示的文件。
    参数
        String name,File file   写入文件的目的地
        boolean append     追加写的·开关
            true,打开追加写,创建对象不会覆盖原文件,继续在末尾写数据
            false,不打开追加写,创建对象会覆盖原文件,
    换行
        windows   \r\n
        linux     /n
        mac       /r
*/
public class Demo03 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("F:\\makedown\\ceshi\\c.txt",true);
        for (int i = 0; i < 10; i++) {
            fos.write("你好".getBytes());
            fos.write("\r\n".getBytes());
        }

        fos.close();
    }
}

字节输入流

package iotext;

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

/*
    java.io.InputStream ,字节输入流
    这个抽象类是表示输入字节流的所有类的超类。

    定义了所有子类的共性方法
        abstract int read() 从输入流读取数据的下一个字节。
        int read(byte[] b)  从输入流读取一些字节数,并将它们存储到缓冲区 b
        void close()        关闭此输入流并释放与流相关联的任何系统资源

    java.io.FileInputStream  extends InputStream
    FileInputStream,文件字节输入流
    作用,把硬盘文件中的数据读取到内存中使用

    构造方法
        FileInputStream(File file)
        FileInputStream(String name)
        参数
            读取文件的数据源
            String name   文件路径
            File file     文件
    构造方法的作用
        1.会创建一个FileInputStream对象
        2.会把FileInputStream对象,指定构造方法中要读取的文件件

    读取数据的原理(硬盘-->内存)
        java程序-->JVM-->OS-->OS调用读取方法-->读取文件
    读取数据步骤
        1.创建一个FileInputStream对象,构造方法中需要绑定数据源
        2.使用FileInputStream对象中的方法,read,读取文件
        3.释放资源

*/
public class Inputstream {
    public static void main(String[] args) throws IOException {
        //1.创建一个FileInputStream对象,构造方法中需要绑定数据源
        FileInputStream fis = new FileInputStream("F:\\makedown\\ceshi\\b.txt");
        //2.使用FileInputStream对象中的方法,read,读取文件
        //int read = fis.read();
       // System.out.println(read);

        int l=0;
        while((l=fis.read())!=-1){//结束标记-1
            //int read = fis.read();
            System.out.print((char) l);
        }
        //3.释放资源
        fis.close();
    }
}
一次读取多个

在这里插入图片描述

package iotext;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/*
    一次读取多个字节
        int read(byte[] b) 从该输入流读取多个字节的数据存储到数组中。
    明确两件事
        方法的参数byte[] b的作用
            起到缓冲作用,存储每次读取到的字节数
            数组长度一般定义为1024(1kb),或者1024的整数倍
        方法的返回值int是什么
            每次读取到的有效字节个数
    String的构造方法
        String(byte[] bytes)  把字节数组转换为字符串
        String(byte[] bytes, int offset, int length) 把字节数组转换为字符串,offset开始索引,length转换的长度
*/
public class Demo05 {
    public static void main(String[] args) throws IOException {
        //1.创建一个FileInputStream对象,构造方法中需要绑定数据源
        FileInputStream fis = new FileInputStream("F:\\makedown\\ceshi\\c.txt");
        //2.使用FileInputStream对象中的方法,read,读取文件
        /*byte[] bytes =new byte[5];
        int read = fis.read(bytes);
        System.out.println(read);
        String s=new String(bytes);
        System.out.println(s);*/

        byte[] bytes =new byte[1024];
        int read = fis.read(bytes);
        for (int i = 0; i < read; i++) {
            String s=new String(bytes);
            System.out.print(s);
        }

        //3.释放资源
        fis.close();
    }
}
练习,文件的复制
package iotext;
/*
    1.创建一个字节输入流对象
    2.创建一个字节输出流对象
    3.使用read方法,把文件读取到内存
    4.使用write方法,把文件存储到硬盘
    5.释放资源
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) throws IOException {
        //先读后写, 
        //读取文件
        FileInputStream fis = new FileInputStream("F:\\makedown\\ceshi\\c.txt");
        byte[] bytes = new byte[1024];
        int read = fis.read(bytes);

        //存储文件
        FileOutputStream fos = new FileOutputStream("F:\\ceshi\\c.txt");
        fos.write(bytes);

        //释放资源
        fos.close();
        fis.close();
    }
}
package iotext;
/*
    1.创建一个字节输入流对象
    2.创建一个字节输出流对象
    3.使用read方法,把文件读取到内存
    4.使用write方法,把文件存储到硬盘
    5.释放资源
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

        FileInputStream fis = new FileInputStream("F:\\makedown\\tu\\1.png");
        FileOutputStream fos = new FileOutputStream("F:\\ceshi\\1.png");

        //速度慢
        /*
        int l=0;
        while((l=fis.read())!=-1){
            fos.write(l);
        }
        */

        //改进版,速度快
        byte[] bytes = new byte[1024];
        int len=0;
        while((len=fis.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }

        //释放资源
        fos.close();
        fis.close();
    }
}
读取中文问题

当使用字节流读取文本时可能遇到一些问题,当遇到中文字符时,可能显示不全中文,那是因为中文可能占用多个字节储存。所以java提供了一些字符流内,以字符为单位读写数据,专用于处理文本文件。

字符流

读取字符
package iotext;

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

/*
    java.io.Reader ,字符输入流,是字符输入流最顶层的父类,定义了一些共性的成员方法,是一个抽象类

    共性的方法
        int read() 读一个字符,并返回
        int read(char[] cbuf) 一次读取多个字符,将字符读入数组
        abstract void close() 关闭流并释放与之相关联的任何系统资源

    java.io.FileReader extends InputStreamReader extends Reader
    FileReader,文件字符输入流
    作用,把硬盘文件中的数据以字符的方式读取到内存中
    构造方法
        FileReader(File file)
        FileReader(String fileName)
        参数,读取文件的数据源
            File file,一个文件
            String fileName,文件路径
        FileReader构造方法的作用
            1.创建一个FileReader对象
            2.会把FileReader对象指向要读取的文件
    字符输入流的使用步骤
        1.创建一个FileReader对象,在其构造方法中绑定要读取的文件
        2.使用FileReader中的read方法读取文件
        3.释放资源
*/
public class readtext {
    public static void main(String[] args) throws IOException {

        //1.创建一个FileReader对象,在其构造方法中绑定要读取的文件
        FileReader fs = new FileReader("F:\\makedown\\ceshi\\a.java");
        //2.使用FileReader中的read方法读取文件
        /*
        int len=0;
        while((len=fs.read())!=-1){
            System.out.print((char)len);//汉字出现???,可能是电脑建立文件使用的不是utf-8,可以使用notepad++修改即可
        }
        */
        //int read(char[] cbuf) 一次读取多个字符,将字符读入数组
        char[] chars = new char[1024];//存储读取到的多个字符
        int len=0;
        while((len=fs.read(chars))!=-1){
            /*
            String类的构造方法
            String(char[] value),把字符数组转换为字符串
            String(char[] value, int offset, int count) 把字符数组转换为字符串,offset字符数组开始,count转换几个

            */
            System.out.print(new String(chars,0,len));//汉字出现???,可能是电脑建立文件使用的不是utf-8,可以使用notepad++修改即可
        }

        fs.close();
    }
}
写入字符
package iotext;

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

/*
    java.io.writer:字符输出流,是所有字符输出流的最顶层的父类,是一个抽蒙类共性的成员方法:
        void write(intc)写入单个字符。
        void write(char[] cbuf)写入字符数组。
        obstract void write(chor[] cbuf, int off, int len)写入字符数组的某-一部分, off数组的开始索引len写的字符个数。
        void write(String str)写入字符串。
        void write(String str,int off, intlen)写入字符串的某一部分,off字符串的开始索引len写的字符个数。
        void flush( )刷新该流的缓冲,
        void close()关闭此流,但要先刷新它。

    java. io.Filewriter extends Outputstreamwriter extends writer
    Filewriter:文件字符输出流
        作用:把内存中字符数据写入到文件中

    构造方法:
            FileWriter(File file)
            FileWriter(String fileName)
            参数:写入数据的目的地
                String fileName:文件的路径
                File file,是一个文件
    构造方法的作用
        1.创建一个FileWriter对象,
        2.会根据构造方法中的文件、文件路径,创建文件
        3.会把FileWriter对象指向创建好的对象

    字符输出流的使用步骤
        1.创建FileWriter对象,在构造方法中绑定要写入数据的目的地
        2.使用FileWriter对象中的方法,把数据写入内存缓冲区(字符转换为字节的过程)
        3.使用FileWriter对象中的方法flush,把内存缓冲区中的数据,刷新到文件中
        4.释放资源,也会把未写入的文件从内存放入硬盘
*/
public class Zifuxieruliu {
    public static void main(String[] args) throws IOException {

        // 1.创建FileWriter对象,在构造方法中绑定要写入数据的目的地
        FileWriter fw = new FileWriter("F:\\makedown\\ceshi\\e.txt");
        //2.使用FileWriter对象中的方法,把数据写入内存缓冲区(字符转换为字节的过程)
        fw.write(97);
        //3.使用FileWriter对象中的方法flush,把内存缓冲区中的数据,刷新到文件中
        fw.flush();
        //4.释放资源
        fw.close();
    }
}
关闭与刷新的区别
  • close,先刷新缓冲区,再通知系统关闭资源,释放后流对象无法在使用
  • flush,刷新缓冲区,流对象可以继续使用
字符输出流写数据的其他方法
package iotext;

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

/*
    字符输出流写字符的其他方法
        void write(char[] cbuf)写入字符数组。
        obstract void write(chor[] cbuf, int off, int len)写入字符数组的某-一部分, off数组的开始索引len写的字符个数。
        void write(String str)写入字符串。
        void write(String str,int off, intlen)写入字符串的某一部分,off字符串的开始索引len写的字符个数。
*/
public class Zifuxieruliu02 {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("F:\\makedown\\ceshi\\f.txt");

        //void write(char[] cbuf)写入字符数组。
        char[] cs={'a','b','c','d','e'};
        fw.write(cs);
        //obstract void write(chor[] cbuf, int off, int len)写入字符数组的某-一部分, off数组的开始索引len写的字符个数
        fw.write(cs,1,3);
        //void write(String str)写入字符串
        fw.write("鱼汤");
        //void write(String str,int off, intlen)写入字符串的某一部分,off字符串的开始索引len写的字符个数
        fw.write("yutang挺好喝",6,3);

        fw.close();
    }
}
续写和换行
package iotext;

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

/*
    续写和换行
    续写,追加写,使用两个参数的构造方法
        FileWriter(File file, boolean append)
        FileWriter(String fileName, boolean append)
        参数
            File file,String fileName,写入数据目的地
            boolean append,续写开关
    换行,换行符号
        windows,\r\n
        linux,/n
        mac,/r
*/
public class Zifuxieruliu02xuxiehuanghang {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("F:\\makedown\\ceshi\\f.txt",true);

        for (int i = 0; i < 10; i++) {
            fw.write("hello world"+i+"\r\n");
        }

        fw.close();
    }
}
流中异常的处理
package iotext;

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

/*
    在jdk1.7之前,使用 try catch finally来处理
    格式
        try{
            可能产生异常的代码
        }catch(异常类变量 变量名) {
            处理的逻辑
        }finally{
            一定会指定的代码
            释放资源
        }
*/
public class Trycatchtext {
    public static void main(String[] args) {
        //提高fw的作用域,让finally可以使用
        //定义变量时可以没有值,但是在使用时需要赋值
        // fw = new FileWriter("F:\\makedown\\ceshi\\f.txt",true);,执行失败,fw没有值,就会是fw.close();也出现异常
        FileWriter fw=null;
        try{
            fw = new FileWriter("w:\\makedown\\ceshi\\f.txt",true);

            for (int i = 0; i < 10; i++) {
                fw.write("hello world"+i+"\r\n");
            }

        }catch(IOException e){
            //处理的逻辑
            System.out.println(e);
        }finally {
            //一定会指定的代码
            //创建资源失败fw=null,会出现空指针异常,需要增加一个判断,不是null再释放资源
            if (fw!=null){
                try {

                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
JDK7与JDK9处理异常的逻辑
  • JDK7
package iotext;

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

/*
    JDK7的新特性
    再try 后面添加了一个括号,可以定义流对象
    流对象的作用域为,整个try catch语句
    try中代码执行完毕会自动释放流对象,不用再写finally
    格式
        try(定义流定向···){
            可能产生异常的代码
        }catch(异常类变量 变量名) {
            处理的逻辑
        }
*/
public class Trycatchtext02 {
    public static void main(String[] args) {

        try(FileInputStream fis = new FileInputStream("F:\\makedown\\tu\\1.png");
            FileOutputStream fos = new FileOutputStream("F:\\ceshi\\1.png");){

            //可能产生异常的代码
            int l=0;
            while((l=fis.read())!=-1) {
                fos.write(l);
            }
        }catch (IOException e){
            //处理的逻辑
            System.out.println(e);
        }
    }
}
  • JDK9
package iotext;

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

/*
    JDK9的新特性
    try的前面可以定义流对象
    在try的后面括号,引入流对象的名称()
    在try代码执行结束后,也会释放掉资源,不用写finally
    格式
        A a=new A;
        B b=new B;
        try(a,b){
            可能产生异常的代码
        }catch(异常类变量 变量名) {
            处理的逻辑
        }
*/
public class Trycatchtext03 {
    public static void main(String[] args) throws FileNotFoundException {

        FileInputStream fis = new FileInputStream("F:\\makedown\\tu\\1.png");
        FileOutputStream fos = new FileOutputStream("F:\\ceshi\\1.png");
        try(fis;fos){//分号

            //可能产生异常的代码
            int l=0;
            while((l=fis.read())!=-1) {
                fos.write(l);
            }
        }catch (IOException e){
            //处理的逻辑
            System.out.println(e);
        }
    }
}

Properties集合

基本使用

package iotext;

import java.util.Properties;
import java.util.Set;

/*
    java.util.Properties 集合,extends Hashtable<Object,Object>   implements Map<K,V>,
    Properties表示一个持久的属性集,Properties可以保存在流中,或者从流中加载
    Properties集合,是一个唯一与IO流结合的集合
        可以使用Properties集合中的方法store,把流中的数据持久化写入到硬盘中去
        可以使用Properties集合中的方法load,把硬盘中的数据(键值对),读取到集合中使用

    属性列表中的每个键及其对应的值都是一个字符串
        Properties集合是一个双列集合,key与value默认都是字符串
*/
public class Demo01propertise {
    public static void main(String[] args) {

        show01();
    }

    /*
       使用Properties集合中的存储数据,遍历取出Properties集合中的数据
       Properties集合是一个双列集合,key与value默认都是字符串
       Properties集合有一些操作字符串的特有方法
            Object setProperty(String key, String value) 相当于 Hashtable方法 put
            String getProperty(String key)    通过key找value值,相当于map集合中的get(key)方法
            Set<String> stringPropertyNames() 返回此属性列表中的一组键,其中键及其对应的值为字符串,相当于map中的keyset方法,把集合放入set集合
    */
    private static void show01() {
        //创建Properties集合
        Properties prop = new Properties();
        //Object setProperty(String key, String value) 相当于 Hashtable方法 put
        prop.setProperty("张三","160");
        prop.setProperty("李四","168");
        prop.setProperty("王五","165");
        //遍历集合
        Set<String> set = prop.stringPropertyNames();
        for (String s : set) {
            String value = prop.getProperty(s);
            System.out.println(s+"="+value);
        }

    }
}

store方法

package iotext;

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

/*
    java.util.Properties 集合,extends Hashtable<Object,Object>   implements Map<K,V>,
    Properties表示一个持久的属性集,Properties可以保存在流中,或者从流中加载
    Properties集合,是一个唯一与IO流结合的集合
        可以使用Properties集合中的方法store,把流中的数据持久化写入到硬盘中去
        可以使用Properties集合中的方法load,把硬盘中的数据(键值对),读取到集合中使用

    属性列表中的每个键及其对应的值都是一个字符串
        Properties集合是一个双列集合,key与value默认都是字符串
*/
public class Demo02propertise {
    public static void main(String[] args) throws IOException {

        show02();
    }

    /*
        可以使用Properties集合中的方法store,把流中的数据持久化写入到硬盘中去
        void store(OutputStream out, String comments)
        void store(Writer writer, String comments)
        参数
            OutputStream out  ,字节输出流,不可以写中文
            Writer writer      ,字符输出流,可以使用中文
            String comments注释,用来解释文件是干什么用的
                不能使用中文,会产生乱码,默认为Unicode编码,我们电脑一般为GBK
                一般使用空字符串、

        使用步骤
            1.创建Properties集合对象,添加数据
            2.创建字节输出流,字符输出流对象,构造方法中绑定要输出的目的地
            3.使用Properties集合中的store,把流中的数据持久化写入到硬盘中去
            4.释放资源
    */
    private static void show02() throws IOException {

        //1.创建Properties集合对象,添加数据
        Properties prop = new Properties();
        //Object setProperty(String key, String value) 相当于 Hashtable方法 put
        prop.setProperty("张三","160");
        prop.setProperty("李四","168");
        prop.setProperty("王五","165");
        //2.创建字节输出流,字符输出流对象,构造方法中绑定要输出的目的地
        FileWriter fw = new FileWriter("F:\\makedown\\ceshi\\aa.txt");
        //3.使用Properties集合中的store,把流中的数据持久化写入到硬盘中去
        prop.store(fw,null);

        //使用字节流
        prop.store(new FileOutputStream("F:\\makedown\\ceshi\\aa.txt",true),null);

        //4.释放资源
        fw.close();
    }
}

lood方法

package iotext;

import java.io.*;
import java.util.Properties;
import java.util.Set;

/*
    java.util.Properties 集合,extends Hashtable<Object,Object>   implements Map<K,V>,
    Properties表示一个持久的属性集,Properties可以保存在流中,或者从流中加载
    Properties集合,是一个唯一与IO流结合的集合
        可以使用Properties集合中的方法store,把流中的数据持久化写入到硬盘中去
        可以使用Properties集合中的方法lood,把硬盘中的数据(键值对),读取到集合中使用

    属性列表中的每个键及其对应的值都是一个字符串
        Properties集合是一个双列集合,key与value默认都是字符串
*/
public class Demo03propertise {
    public static void main(String[] args) throws IOException {

        show03();
    }

    /*
        可以使用Properties集合中的方法load,把硬盘中的数据(键值对),读取到集合中使用
        void load(InputStream inStream)
        void load(Reader reader)
        参数
            InputStream inStream  ,字节输入流,不能读取中文键值对
            Reader reader      ,字符输入流,能读取中文键值对

        使用步骤
            1.创建Properties集合对象,
            2.使用Properties集合中的load,把硬盘中的数据(键值对),读取到集合中使用
            3.遍历Properties集合
        注意
            1.在储存的键值对文件中,键值对的默认连接符号是,=, (空格),或者其他符号
            2.在储存的键值对文件中,可以使用#就行注释,被注释的文件不再被读取
            3.在储存的键值对文件中,默认都是字符串,不用加引号
    */
    private static void show03() throws IOException {

        // 1.创建Properties集合对象,
        Properties prop = new Properties();
        //2.使用Properties集合中的load,把硬盘中的数据(键值对),读取到集合中使用
        prop.load(new FileReader("F:\\makedown\\ceshi\\aa.txt"));
        //3.遍历Properties集合
        Set<String> s = prop.stringPropertyNames();
        for (String s1 : s) {
            String value = prop.getProperty(s1);
            System.out.println(s1+"="+value);
        }
    }
}

缓冲流

字节缓冲输出流

package iotext;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
    java.io.BufferedOutputStream extends FilterOutputStream
    BufferedOutputStream,字节缓冲输出流

    继承自父类的共性成员方法
        void close()                 关闭此输出流并释放与此流相关联的任何系统资源。
        void flush()                 刷新此输出流并强制任何缓冲的输出字节被写出。
        void write(byte[] b)         将 b.length字节从指定的字节数组写入此输出流。
        void write(byte[] b, int off, int len) 从指定的字节数组写入 len个字节,从偏移 off开始输出到此输出流。
        abstract void write(int b)    将指定的字节写入此输出流。

    构造方法
        BufferedOutputStream(OutputStream out) 创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
        BufferedOutputStream(OutputStream out, int size) 创建一个新的缓冲输出流,以便以指定的缓冲区大小将数据写入指定的底层输出流
        参数
            OutputStream out,字节输出流
            我们可以传递FileOutStream,缓冲流会给FileOutStream增加一个缓冲区,提高FileOutStream的写入效率
            int size,指定缓冲流内部的缓冲区的大小,不指定就为默认值

    使用步骤
        1.创建FileOutStream对象,构造方法中绑定要传输的目的地
        2.创建BufferedOutputStream对象,构造方法中传递FileOutStream对象,提高FileOutStream对象的效率
        3.使用BufferedOutputStream对象中的方法write,把数据写入内部缓冲区
        4.使用BufferedOutputStream对象中的方法flush,把内部缓冲区的数据刷新到文件中
        5.释放资源(会先使用flush把文件刷新,然后在释放资源)
*/
public class Demo01bufferstream {

    public static void main(String[] args) throws IOException {
        //1.创建FileOutStream对象,构造方法中绑定要传输的目的地
        FileOutputStream fos = new FileOutputStream("F:\\makedown\\ceshi\\bb.txt");
        //2.创建BufferedOutputStream对象,构造方法中传递FileOutStream对象
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //3.使用BufferedOutputStream对象中的方法write,把数据写入内部缓冲区
        byte[] bs={48,48,49,45};
        bos.write(bs);
        //使用BufferedOutputStream对象中的方法flush,把内部缓冲区的数据刷新到文件中
        bos.flush();
        //释放资源
        bos.close();
    }
}

字节缓冲输入流

package iotext;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/*
    java.io.BufferedInputStream extends FilterInputStream
    BufferedInputStream,字节缓冲输入流

    继承父类的共性方法
        abstract int read() 从输入流读取数据的下一个字节。
        int read(byte[] b)  从输入流读取一些字节数,并将它们存储到缓冲区 b
        void close()        关闭此输入流并释放与流相关联的任何系统资源
    构造方法
        BufferedInputStream(InputStream in)
        BufferedInputStream(InputStream in, int size)
        参数
            InputStream in,字节输入流
            我们传递FileInputStream对象,可以给FileInputStream对象创建一个缓冲区,提高FileInputStream的效率
            int size,指缓冲流内部缓冲区的大小,不指定就是默认值

    使用步骤
        1.创建FileInputStream对象,构造方法中传递目的地址
        2.创建BufferedInputStream对象,构造方法中传递FileInputStream对象
        3.创建BufferedInputStream对象,使用read方法读取文件
        4.释放资源
*/
public class Demo02bufferstream {
    public static void main(String[] args) throws IOException {
        //1.创建FileInputStream对象,构造方法中传递目的地址
        FileInputStream fis = new FileInputStream("F:\\makedown\\ceshi\\bb.txt");
        //2.创建BufferedInputStream对象,构造方法中传递FileInputStream对象
        BufferedInputStream bis = new BufferedInputStream(fis);
        //3.创建BufferedInputStream对象,使用read方法读取文件
        byte[] cs=new byte[1024];
        int len = 0;
        while((len=bis.read(cs))!=-1){
            System.out.println(new String(cs));
        }
        //4.释放资源
        fis.close();
    }
}

练习复制文件

package iotext;

import java.io.*;

/*
    复制文件
*/
public class Bufferedcopy {
    public static void main(String[] args) throws IOException {
        long s=System.currentTimeMillis();

        FileInputStream fis = new FileInputStream("F:\\makedown\\tu\\1-1.jpg");
        FileOutputStream fos = new FileOutputStream("F:\\ceshi\\1-1.jpg");

        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] cs=new byte[1024];
        int len = 0;
        while((len=bis.read(cs))!=-1){
           fos.write(cs,0,len);
        }

        bos.close();
        bis.close();
        long ss=System.currentTimeMillis();
        System.out.println(ss-s);
    }
}

字符缓冲输出流

package iotext;

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

/*
    java.io.BufferedWriter extends Writer
    BufferedWriter,字符缓冲输出流

    继承自父类的共性方法
        void write(intc)写入单个字符。
        void write(char[] cbuf)写入字符数组。
        obstract void write(chor[] cbuf, int off, int len)写入字符数组的某-一部分, off数组的开始索引len写的字符个数。
        void write(String str)写入字符串。
        void write(String str,int off, intlen)写入字符串的某一部分,off字符串的开始索引len写的字符个数。
        void flush( )刷新该流的缓冲,
        void close()关闭此流,但要先刷新它。

    构造方法
        BufferedWriter(Writer out)
        BufferedWriter(Writer out, int sz)
        参数
            Writer out,字符输出流
            我们可以输入FileWriter,给FileWriter增加一个缓冲区,提高效率
            int sz,缓冲区大小,不写为默认大小
    特有的成员方法
        void newLine() 写一行行分隔符
        windows,\r\n
        linux,/n
        mac,/r

    使用步骤
        1.调用字符缓冲输出流对象,构造方法中传递字符输出流
        2.调用字符缓冲输出流中的方法write,把数据写入内存缓冲区
        3.调用字符缓冲输出流中的方法flush,把内存缓冲区的文件写到硬盘上
        4.释放资源
*/
public class BufferWrite {
    public static void main(String[] args) throws IOException {
        //1.调用字符缓冲输出流对象,构造方法中传递字符输出流
        BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\makedown\\ceshi\\e.txt"));
        //2.调用字符缓冲输出流中的方法write,把数据写入内存缓冲区
        bw.write("你好");
        bw.newLine();//换行
        bw.write("你好");
        // 3.调用字符缓冲输出流中的方法flush,把内存缓冲区的文件写到硬盘上
        bw.flush();
        //4.释放资源
        bw.close();

    }
}

字符缓冲输出流

package iotext;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/*
    java.io.BufferedReader extends Reader
    BufferedReader,字符缓冲输入流

    继承自父类的方法
        int read() 读一个字符,并返回
        int read(char[] cbuf) 一次读取多个字符,将字符读入数组
        abstract void close() 关闭流并释放与之相关联的任何系统资源
    构造方法
        BufferedReader(Reader in)
        BufferedReader(Reader in, int sz)
        参数
            Reader in,字符输入流
            我们可以使用FileReader对象,缓冲流会给FileReader对象增加一个缓冲区,提高效率
            int sz,缓冲区的大小,不写就是默认值
    特有方法
        String readLine() 读一行文字
        一行被视为由换行符('\ n'),回车符('\ r')中的任何一个或随后的换行符终止。
        返回值
            包含行的内容的字符串,不包括任何行终止字符,如果已达到流的末尾,则为null
   使用步骤
        1.创建字符缓冲输入流对象,构造方法中传入字符流对象
        2.使用字符缓冲输入流对象的方法read,读取文件
        3.释放资源
*/
public class Bufferedread {
    public static void main(String[] args) throws IOException {
        //1.创建字符缓冲输入流对象,构造方法中传入字符流对象
        BufferedReader br = new BufferedReader(new FileReader("F:\\makedown\\ceshi\\e.txt"));
        //2.使用字符缓冲输入流对象的方法read,读取文件
        /*
        int len=0;
        char[] cs=new char[1024];
        while ((len=br.read(cs))!=-1){
            System.out.println(cs);
        }
        */
        String s;
        while((s = br.readLine())!=null){
            System.out.println(s);
        }

        br.close();
    }
}

转换流

转换输出流

package iotext;

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

/*\
    java.io.OutputStreamWriter extends Writer
    OutputStreamWriter是字符流通向字节流的桥梁,可以使用charSet将需要写入的字符转换为字节,(把能看懂的变为看不懂的)

    继承自父类的方法
        void write(intc)写入单个字符。
        void write(char[] cbuf)写入字符数组。
        obstract void write(chor[] cbuf, int off, int len)写入字符数组的某-一部分, off数组的开始索引len写的字符个数。
        void write(String str)写入字符串。
        void write(String str,int off, intlen)写入字符串的某一部分,off字符串的开始索引len写的字符个数。
        void flush( )刷新该流的缓冲,
        void close()关闭此流,但要先刷新它。
    构造方法
        OutputStreamWriter(OutputStream out) 创建一个使用默认字符编码的OutputStreamWriter
        OutputStreamWriter(OutputStream out, String charsetName) 创建一个使用命名字符集的OutputStreamWriter
        参数
            OutputStream out,字节输出流,可以用来写转换之后字节到文件
            String charsetName,指定编码表名称,不区分大小写,不指定默认为utf-8
    使用步骤
        1.创建OutputStreamWriter对象,构造方法中传递字节输出流和指定编码表格式
        2.使用OutputStreamWriter对象中的方法Write,把字符转换为字节存储到缓冲区中
        3.使用OutputStreamWriter对象中的方法flush,把缓冲区中字节的刷新到文件中
        4.释放资源
*/
public class OutputStreamWriterText {
    public static void main(String[] args) throws IOException {

        write_utf_8();
    }


    private static void write_utf_8() throws IOException {
        //1.创建OutputStreamWriter对象,构造方法中传递字节输出流和指定编码表格式
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("F:\\java-code\\com.a\\b.txt"),"gbk");
        //2.使用OutputStreamWriter对象中的方法Write,把字符转换为字节存储到缓冲区中
        osw.write("你好啊");
        //3.使用OutputStreamWriter对象中的方法flush,把缓冲区中字节的刷新到文件中
        osw.flush();
        //4.释放资源
        osw.close();
    }
}

转换输入流

package iotext;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/*
    java.io.InputStreamReader extends Reader
    InputStreamReade,是字节流通字符流的桥梁,使用指定的charset是字节并将其接码为字符

    继承自父类的方法
        int read() 读一个字符,并返回
        int read(char[] cbuf) 一次读取多个字符,将字符读入数组
        abstract void close() 关闭流并释放与之相关联的任何系统资源
    构造方法
        InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader
        InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader
        参数
            InputStream in,字节输入流,从文件中读入字节
            String charsetName,指定编码格式,不区分大小写,默认utf-8
    使用步骤
        1.创建InputStreamReade对象,构造方法中传递字节输入流
        2.使用InputStreamReade对象中的read,把文件读入
        3.释放资源
    注意
        构造方法中指定的编码表名称,要和文件编码相同不然会发生乱码
*/
public class InputStreamReaderText {
    public static void main(String[] args) throws IOException {
        read_utf_8();
    }

    private static void read_utf_8() throws IOException {
        //1.创建InputStreamReade对象,构造方法中传递字节输入流
        InputStreamReader isr = new InputStreamReader(new FileInputStream("F:\\java-code\\com.a\\b.txt"),"gbk");
        //2.使用InputStreamReade对象中的read,把文件读入
        int len=0;
        char[] cs=new char[1024];
        while ((len=isr.read(cs))!=-1){
            System.out.println(new String(cs,0,len));//后面没有空格
        }
        isr.close();
    }
}

练习转换文件编码

  • 将GBK编码的文件转换为utf-8
package iotext;

import java.io.*;

/*
    将GBK转换为utf-8
    1.读取文件,转换为字符
    2.把字符转换为相应格式,写入硬盘
    3.释放资源

*/
public class Zhuanhuanzifu {
    public static void main(String[] args) throws IOException {
        zhuanhuan();
    }

    private static void zhuanhuan() throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream("F:\\java-code\\com.a\\b.txt"),"gbk");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("F:\\java-code\\com.a\\bb.txt"),"utf-8");

        //读取文件
        int len=0;
        char[] cs=new char[1024];
        while ((len=isr.read(cs))!=-1){
            //2.把字符转换为相应格式,写入硬盘
            osw.write(cs,0,len);
        }
        osw.flush();
        osw.close();
        isr.close();
    }
}

序列化流与反序列化流

序列化流

package iotext;

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

/*
    java.io.ObjectOutputStream extends OutputStream
    ObjectOutputStream,对象序列化流
    把对象以流的方式写入文件中保存

    构造方法
        ObjectOutputStream(OutputStream out) 创建一个写入指定的OutputStream的ObjectOutputStream
        参数
            OutputStream out,字节输出流
    特有成员方法
        void writeObject(Object obj) 将指定的对象写入ObjectOutputStream

    使用步骤
        1.创建ObjectOutputStream对象,在构造方法中传递字节输出流
        2.使用ObjectOutputStream对象中的方法writeObject,把对象写入文件中
        3.释放资源


    序列化和反序列化的时候,会抛出NotSerializableException,没有序列化异常
    类的序列化由实现java.io.Serializable接口的类启用,不实现此接口的类将不会使任何状态序列化或反序列化
    Serializable接口,也叫标记性接口
        要序列化和反序列化的时候,就要实现这个接口,就会给类添加一个标记
        没有就会抛出NotSerializableException异常

*/
public class ObjectOutputStreamText {
    public static void main(String[] args) throws IOException {
        //1.创建ObjectOutputStream对象,在构造方法中传递字节输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\java-code\\com.a\\aa.txt"));
        //2.使用ObjectOutputStream对象中的方法writeObject,把对象写入文件中
        oos.writeObject(new Person("你好啊",18));
        //3.释放资源
        oos.close();
    }
}
/*
package iotext;

import java.io.Serializable;
     序列化和反序列化的时候,会抛出NotSerializableException,没有序列化异常
    类的序列化由实现java.io.Serializable接口的类启用,不实现此接口的类将不会使任何状态序列化或反序列化
    Serializable接口,也叫标记性接口
        要序列化和反序列化的时候,就要实现这个接口,就会给类添加一个标记
        没有就会抛出NotSerializableException异常

public class Person implements Serializable {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.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;
    }

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

 */

反序列化流

package iotext;

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

/*
    java.io.ObjectInputStream extends InputStream
    ObjectInputStream,对象反序列化流

    构造方法
        ObjectInputStream(InputStream in) 创建从指定的InputStream读取的ObjectInputStream
        参数
            InputStream in,字节输入流
    特有成员方法
        Object readObject() 从ObjectInputStream读取一个对象

    使用步骤
        1.创建ObjectInputStream对象,在构造方法中传递字节输入流
        2.使用ObjectInputStream对象的方法readObject,读取文件中的对象
        3.释放资源
        4.使用读出的数据
*/
public class ObjectInputStreamText {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //1.创建ObjectInputStream对象,在构造方法中传递字节输入流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\java-code\\com.a\\aa.txt"));
        //2.使用ObjectInputStream对象的方法readObject,读取文件中的对象
        Object s=ois.readObject();
        //.释放资源
        ois.close();
        //4.使用读出的数据
        System.out.println(s);

        Person s1 = (Person) s;
        System.out.println(s1.getName()+s1.getAge());
    }
}
/*
package iotext;

import java.io.Serializable;
     序列化和反序列化的时候,会抛出NotSerializableException,没有序列化异常
    类的序列化由实现java.io.Serializable接口的类启用,不实现此接口的类将不会使任何状态序列化或反序列化
    Serializable接口,也叫标记性接口
        要序列化和反序列化的时候,就要实现这个接口,就会给类添加一个标记
        没有就会抛出NotSerializableException异常

public class Person implements Serializable {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.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;
    }

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

 */

transient关键字

  • 被transient关键字修饰,不能被序列化
  • 被static修饰的也不能被序列化,被序列化的都是对象

InvalidClassException异常

在这里插入图片描述

package iotext;

import java.io.Serializable;

/*
     序列化和反序列化的时候,会抛出NotSerializableException,没有序列化异常
    类的序列化由实现java.io.Serializable接口的类启用,不实现此接口的类将不会使任何状态序列化或反序列化
    Serializable接口,也叫标记性接口
        要序列化和反序列化的时候,就要实现这个接口,就会给类添加一个标记
        没有就会抛出NotSerializableException异常
*/
public class Person implements Serializable {
    static final long serialVersionUID = 2L;//InvalidClassException,解决办法
    private String name;
    public int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.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;
    }

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

练习保存、取出对象

package iotext;

import java.io.*;
import java.util.ArrayList;

/*
    练习,序列化集合
        当我们想在文件中保存多个文件时
        可以把多个对象存储到集合中
        对集合进行序列化与反序列化

    分析
        1.定义一个储存Person对象的ArrayList集合
        2.往ArrayList集合中储存Person对象
        3.创建一个序列化流ObjectOutputStream对象
        4.使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
        5.创建一个反序列化对象ObjectInputStream
        6.使用ObjectInputStream对象的方法readObject,对集合进行反序列化
        7.把Object类型的集合转换为ArrayList类型
        8.遍历ArrayList集合
        9.释放资源
*/
public class XuliehuaText {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //1.定义一个储存Person对象的ArrayList集合
        ArrayList<Person> ar = new ArrayList<>();
        //2.往ArrayList集合中储存Person对象
        ar.add(new Person("张三",18));
        ar.add(new Person("李四",19));
        ar.add(new Person("王五",20));
        //3.创建一个序列化流ObjectOutputStream对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\java-code\\com.a\\XuliehuaText.txt"));
        //4.使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
        oos.writeObject(ar);
        //5.创建一个反序列化对象ObjectInputStream
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\java-code\\com.a\\XuliehuaText.txt"));
        //6.使用ObjectInputStream对象的方法readObject,对集合进行反序列化
        Object o = ois.readObject();
        //7.把Object类型的集合转换为ArrayList类型
        ArrayList<Person> n=(ArrayList)o;
        //8.遍历ArrayList集合
        for (Person o1 : n) {
            System.out.println(o1.getName()+o1.getAge());
        }
        // 9.释放资源

        ois.close();
        oos.close();
    }
}

打印流

package iotext;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

/*
     java.io.PrintStream,打印流
        为其它输出流添加了功能,使他们能够方便的打印各种数据值表示形式
    PrintStream的特点
        1.只负责数据的输出,不负责读入
        2.与其他输出流不同,永远不会抛出IOException异常
        3.有特有方法print、println
            void print(任意类型的数据)
            void println(任意类型的数据并换行)
    构造方法
        PrintStream(File file),输出的目的地是一个文件
        PrintStream(OutputStream out),输出的目的地是一个字节输出流
        PrintStream(String fileName),输出的目的地是一个文件路径
    PrintStream extends OutputStream
    继承自父类的成员方法
        void close()                 关闭此输出流并释放与此流相关联的任何系统资源。
        void flush()                 刷新此输出流并强制任何缓冲的输出字节被写出。
        void write(byte[] b)         将 b.length字节从指定的字节数组写入此输出流。
        void write(byte[] b, int off, int len) 从指定的字节数组写入 len个字节,从偏移 off开始输出到此输出流。
        abstract void write(int b)    将指定的字节写入此输出流。
    注意
        如果使用继承自父类的方法write,查看数据时会查看编码表  97->a
        使用自己的print、println,数据会原样输出               97->97

    可以改变打印流输出目的地
        输出语句,默认输出为控制台
        使用static void setOut(PrintStream out),可以把PrintStream out改为目的文件

*/
public class PrintStreamText {
    public static void main(String[] args) throws FileNotFoundException {

        //创建对象
        PrintStream ps = new PrintStream("F:\\java-code\\com.a\\print.txt");
        //使用自己的print、println,数据会原样输出
        ps.println(97);
        //如果使用继承自父类的方法write,查看数据时会查看编码表  97->a
        ps.write(97);
        //使用static void setOut(PrintStream out),可以把PrintStream out改为目的文件
        System.setOut(ps);
        System.out.println(",我不会出现在控制台");
        ps.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值