Java Io

 1、流的概念和作用  

  1.1 流的概念

   Java中将输入输出抽象称为流,就好像水管,将两个容器连接起来。流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流.

 1.2 流的作用

   为数据源和目的地建立一个输送通道。

2、Io流的体系及分类

   

 1、File(文件特征与管理):用于文件或者目录的描述信息,例如生成新目录,修改文件名,删除文件,判断文件所在路径等。
 2、InputStream(二进制格式操作):抽象类,基于字节的输入操作,是所有输入流的父类。定义了所有输入流都具有的共同特征。
 3、OutputStream(二进制格式操作):抽象类。基于字节的输出操作。是所有输出流的父类。定义了所有输出流都具有的共同特征。
 4、Reader(文件格式操作):抽象类,基于字符的输入操作。
 5、Writer(文件格式操作):抽象类,基于字符的输出操作。
 6、RandomAccessFile(随机文件操作):一个独立的类,直接继承至Object.它的功能丰富,可以从文件的任意位置进行存取(输入输出)操作。

字符流和字节流

 1、字节流:数据流中最小的数据单元是字节
 2、字符流:数据流中最小的数据单元是字符, Java中的字符是Unicode编码,一个字符占用两个字节。
输入流和输出流
 1、输入流:程序从输入流读取数据源。数据源包括外界(键盘、文件、网络…),即是将数据源读入到程序的通信通道(文件--->程序)
 2、输出流:程序向输出流写入数据。将程序中的数据输出到外界(显示器、打印机、文件、网络…)的通信通道(程序--->文件)。

3、流的使用

 1.1、File类 

 基本方法的使用

public static void FiletestDemo() {
        System.out.println(File.separator);  //名称分隔符 \(windows)  /(linux 等)
        System.out.println(File.pathSeparator);  //  路径分隔符  ;

        //相对路径构建的两种方式
        System.out.println("相对路径!!!!!!!!");
        String path = "E:\\BaiduNetdiskDownload";
        String name = "a.txt";
        //第一种方式:
        File file = new File(path, name);
        //第二种方式
        File file1 = new File(new File(path), name);

        //绝对路径的构建方式
        File file2 = new File("E:\\BaiduNetdiskDownload\\a.txt");
    }

递归遍历文件

    /**
     * 递归遍历文件
     */
    public static void printName(File src) {
        if (null == src || !src.exists()) {
            return;
        }
        System.out.println(src.getAbsolutePath());
        if (src.isDirectory()) { //文件夹
            for (File sub : src.listFiles()) {
                printName(sub);
            }

        }
    }

 1.2、字节流 (可以处理一切文本,视频,音频等)

 输入流:InputStream  FileInputStream  ByteInputStream  

 输出流:OutputStream FileOutputStream ByteOutputStream

   

/**
 * 字节输入流
 */
public class FileStreamDemo {

    public static void main(String[] args) throws IOException {
        FileUtil.copyDir(new File("D:\\a"), new File("D:/d"));
    }

    /**
     * 读取文件
     */
    public static void readFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int len = 0;
        StringBuffer sb = new StringBuffer();
        while (-1 != (len = is.read(bytes))) {
            String str = new String(bytes, 0, len);
            sb.append(str);
        }
        System.out.println(sb.toString());

    }

    /**
     * 向文件中写入内容
     */
    public static void writeFile(File file) throws IOException {
        OutputStream os = new FileOutputStream(file, true);
        String str = "你好的ad额的的!!!!!!!!!";
        byte[] bytes = str.getBytes();
        os.write(bytes, 0, bytes.length);
        os.close();
    }

    /**
     * 源文件
     * 目标文件
     * 拷贝文件
     */
    public static void copyFile(File srcFile, File descFile) {
        try {
            if (srcFile.isFile()) {
                InputStream is = new FileInputStream(srcFile);
                OutputStream os = new FileOutputStream(descFile, true);
                byte[] bytes = new byte[1024];
                int len = 0;
                while (-1 != (len = is.read(bytes))) {
                    os.write(bytes, 0, len);
                }
                os.flush();
                os.close();
                is.close();
            } else {
                throw new RuntimeException("不是文件呢");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 工具类

public class FileUtil {

    /**
     * 拷贝文件夹
     * 如果是文件就直接拷贝文件
     * 如果是文件夹就先创建文件夹
     * @param srcFile
     * @param descFile
     */
    public static void copyDir(File srcFile,File descFile){
         if (srcFile.isFile()){
             copyFile(srcFile,descFile);
         }else if (srcFile.isDirectory()){
             descFile.mkdir();
             for (File sub:srcFile.listFiles()){
                 copyDir(sub,new File(descFile,sub.getName()));
             }
         }
    }


    /**
     * 拷贝文件
     *
     * @param src
     * @param desc
     */
    public static void copyFile(String src, String desc) {
        copyFile(new File(src), new File(desc));
    }

    /**
     * 拷贝文件
     *
     * @param srcFile  源文件
     * @param descFile 目标文件
     */
    public static void copyFile(File srcFile, File descFile) {

        try {
            if (srcFile.isFile()) {
                InputStream is = new FileInputStream(srcFile);
                OutputStream os = new FileOutputStream(descFile);
                byte[] bytes = new byte[1024];
                int len = 0;
                while (-1 != (len = is.read(bytes))) {
                    os.write(bytes, 0, len);
                }

                os.flush();
                os.close();
                is.close();
            }


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

    }
}

 

/**
*ByteInputStream ByteOutStream
*/ public class otherByteArraysDemo { public static void main(String[] args) throws IOException { //readArrays(writeArrays()); byte[] bytes = toFileByteArray(new File("D:\\a\\dsfs\\a.txt")); toArrayFile(bytes, "D:\\a\\dsfs\\b.txt"); } public static byte[] writeArrays() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); String str = "你是一个好人"; byte[] bytes = str.getBytes(); byteArrayOutputStream.write(bytes, 0, bytes.length); byte[] re = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); return re; } public static void readArrays(byte[] src) throws IOException { InputStream is = new BufferedInputStream(new ByteArrayInputStream(src)); byte[] bytes = new byte[1024]; int len = 0; String strArray = null; while (-1 != (len = is.read(bytes))) { strArray = new String(bytes, 0, len); } System.out.println(strArray.toString()); is.close(); } /** * 1、文件 -->>>程序->字节数组 * 以程序为中心 出去就是输出流 ,流入就是输入流 * 涉及到文件输入流 --->>字节数组输出流 */ public static byte[] toFileByteArray(File src) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(src)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] desc = null; byte[] bytes = new byte[1024]; int len = 0; while (-1 != (len = is.read(bytes))) { bos.write(bytes, 0, len); } bos.flush(); desc = bos.toByteArray(); is.close(); bos.close(); return desc; } /** * 2、字节数组 --程序->文件 * 字节数组输入流 * 文件输出流 */ public static void toArrayFile(byte[] src, String destPath) throws IOException { InputStream bis = new BufferedInputStream(new ByteArrayInputStream(src)); OutputStream fs = new BufferedOutputStream(new FileOutputStream(destPath)); byte[] bytes = new byte[1024]; int len = 0; while (-1 != (len = bis.read(bytes))) { fs.write(bytes, 0, len); } fs.flush(); fs.close(); bis.close(); } }
 

1.3、字符流(只能处理文本)

  字符输入流:Reader FileReader

  字符输出流:Writer FileWriter 

/**
 * 字符流,只能处理纯文本
 */
public class ReadWriteDemo {
    /**
     * 读文件
     * @param file
     */
    public static void readerFile(File file) {
        try {
            Reader reader = new FileReader(file);
            char[] chars = new char[1024];
            int len = 0;
            StringBuffer sb = new StringBuffer();
            while (-1 != (len = reader.read(chars))) {
                String str = new String(chars, 0, len);
                sb.append(str);
            }
            System.out.println(sb.toString());
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeFile(File file) {
        try {
            Writer writer = new FileWriter(file);
            String str = "asdddddddddddddddddddasda!!!!!!!!@@@@@";
            writer.write(str);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 拷贝文件
     * @param src  源文件
     * @param desc 目标文件
     */
    public static void copyFile(File src, File desc) throws IOException {
        try {
            Reader reader = new FileReader(src);
            Writer writer = new FileWriter(desc);
            char[] chars = new char[1024];
            int len = 0;
            while (-1 != (len = reader.read(chars))) {
                String str = new String(chars, 0, len);
                writer.write(str);
            }
            writer.flush();
            writer.close();
            reader.read();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

 

1.4、处理流(提高性能增强功能)

   解码和编码

/**
 * 编码和解码   
* */ public class bMDemo { public static void main(String[] args) throws Exception { //编码 字符窜----->>字节 String str = new String("你哈的"); byte[] bytes = new byte[0]; try { bytes = str.getBytes("GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(Arrays.toString(bytes)); //解码 字节---->>字符 String strjm = null; try { strjm = new String(bytes, "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(strjm); }

转换流(字节流---->字符流):编码和解码

  输入流:InputStreamReader   解码  

  输入流:OutputStreamWriter  编码  

/**
 * 字节流转换成字符流
 */
public class ZhStreamDemo {

    public static void main(String[] args) throws IOException {
        BufferedReader bf=null;
        BufferedWriter bw=null;
        try {
            bf=new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(new File("D:\\a\\dsfs\\a.txt")))));
            bw=new BufferedWriter(new OutputStreamWriter(new  BufferedOutputStream(new FileOutputStream(new File("D:\\a\\a.txt")))));
            String str=null;
            while (null!=(str=bf.readLine())){
                bw.write(str);
            }

            bw.flush();
            bf.close();
            bw.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}  

缓存流 :提高性能 ,代码见上面

 输入流:BufferedInputStream(字节)       BufferedReader(字符)

 输出流: BufferedOutputStream(字节) BufferedWriter (字符) 

处理基本数据类型流:DataInputStream DataOutputStream

/**
 * 处理流 基本数据类型+字符窜
 */
public class dataStreamDemo {

    /**
     * 从文件读取数据+类型
     */
    public static void read(String destPath) throws IOException {
        //创建源
        File src = new File(destPath);
        //选择流
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(
                        new FileInputStream(src)
                )
        );

        //操作 读取的顺序与写出一致   必须存在才能读取
        //不一致,数据存在问题
        long num2 = dis.readLong();
        double num1 = dis.readDouble();
        String str = dis.readUTF();

        dis.close();
        System.out.println(num2 + "-->" + str);

    }

    /**
     * 数据+类型输出到文件
     */
    public static void write(String destPath) throws IOException {
        double point = 2.5;
        long num = 100L;
        String str = "数据类型";

        //创建源
        File dest = new File(destPath);
        //选择流  DataOutputStream
        DataOutputStream dos = new DataOutputStream(
                new BufferedOutputStream(
                        new FileOutputStream(dest)
                )
        );
        //操作 写出的顺序 为读取准备
        dos.writeDouble(point);
        dos.writeLong(num);
        dos.writeUTF(str);
        dos.flush();

        //释放资源
        dos.close();


    }
}  

处理引用类型流: ObjectInputStream  ObjectOutStream 

public class User implements Serializable {
    private transient String username;
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

/**
 * 序列化和反序列化流
 * 处理引用类型的数据
 */
public class objectStreamDemo {

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

        serial("D:\\a\\dsfs\\a.txt");
        fserial("D:\\a\\dsfs\\a.txt");
    }

    /**
     * 反序列化(文件--->程序)
     *
     * @param src
     */
    public static void fserial(String src) throws IOException, ClassNotFoundException {
        ObjectInputStream os = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(src))));
        Object o = os.readObject();
        if (o instanceof User) {
            User user = (User) o;
            System.out.println(user.getUsername());
            System.out.println(user.getPassword());
        }
        closeDemo.closaAll(os);

    }

    /**
     * 序列化(程序--->文件)
     */
    public static void serial(String destPath) throws IOException {
        User user = new User("asd", "123");
        ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File(destPath))));
        os.writeObject(user);
        closeDemo.closaAll(os);
    }
}

 

关闭流的方法

 

/**
 * 关闭流的公共调用
 */
public class closeDemo {

    public static void closaAll(Closeable... io) {
        for (Closeable temp : io) {
            try {
                if (temp != null) {
                    temp.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static <T extends Closeable> void closeAll(T... io) {
        for (Closeable temp : io) {
            try {
                if (null != temp) {
                    temp.close();
                }
            } catch (Exception e) {
            }
        }
    }
}  

以下的方法使用新增方法不能发生多态

ByteArrayOutputStream  toByteArray()

BufferedReader readerLine()

BufferedWriter newLine();

DataInputStream DataOutputStream

ObjectInputStream ObjectOutputStream

每天进步一丢丢

完成。 

  

  

 

 

 

 

  

 

 

  

 

posted @ 2020-05-03 22:01  阿福聊编程  阅读(152)  评论(0编辑  收藏  举报