第八章 IO

第八章 IO

File类

File类是java.io包中很重要的一个类;

File类的对象可以表示文件,还可以表示目录,在程序中一个File类对象可以代 表一个文件或目录;

File对象可以对文件或目录的属性进行操作,如:文件名、最后修改日期、文件大小等;

File对象无法操作文件的具体数据,即不能直接对文件进行读/写操作。

File类的构造方法

在这里插入图片描述

File类的常用方法
在这里插入图片描述

package com.ffyc.io.file;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/*
       File类  在程序中抽象的表示计算机中的文件和目录(文件夹).
               一个Flie类的对象可以表示一个具体的文件或目录
               File类的对象只表示文件,不能对文件内容进行读写操作

               E:/demo1.txt  绝对路径  完整的路径
               a.txt         相对路径  不是全路径,是两个文件的相对同一个父级的路径

 */
public class FileDemo {
    public static void main(String[] args) {
        File file = new File("E:/demoo");
        System.out.println(file.getAbsoluteFile());//获取文件的绝对路径、
        System.out.println(file.canRead());//文件是否可读
        System.out.println(file.canWrite());//文件是否可写
        File file1=new File("E:/demo1.txt");
        System.out.println(file1.exists());//判断文件是否存在
        if(!file1.exists()){
            try {
                file1.createNewFile();//创建文件
                System.out.println("创建成功");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
        File file2=new File("E:/demo2.txt");
        if(!file2.exists()){
            try {
                file2.createNewFile();
                System.out.println("创建成功");//创建文件
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件路径不合法");
            }
            System.out.println(file2.delete());//删除文件
        }
        System.out.println(file.getName());//获取文件的名字
        System.out.println(file.getParent());//获取文件的父级文件夹
        System.out.println(file.getPath());//获取文件的绝对路径
        System.out.println(file.length());//获取文件的字节大小
        File file3=new File("E:/Demo");
        System.out.println(file3.mkdir());//创建一个文件夹(只有一个目录)
        File file4=new File("E:/Demo1/Demo2/demo3");
        System.out.println(file4.mkdirs());//创建多级目录
        System.out.println(file4.delete());//删除文件夹时文件夹必须没有文件才可以删除成功,并且删除的是最深层的那一个文件夹
        System.out.println(file.lastModified());//返回此抽象路径名表示的文件上次修改的时间。
        System.out.println(new Date(file.lastModified()));//返回此抽象路径名表示的文件上次修改的时间。
        System.out.println(file4.isDirectory());//测试此抽象路径名表示的文件是否为目录。
    }
}

输入及输出的概念

输入输出(I/O)

把电脑硬盘上的数据读到程序中,称为输入,即input,进行数据 的read操作从程序往外部设备写数据,称为输出,即output,进行数据的write操作。

在这里插入图片描述

输入流与输出流

从数据流编码格式上划分为

1)字节流

2)字符流

流按着数据的传输方向分为:

1)输入流:往程序中读叫输入流。

2)输出流:从程序中往外写叫输出流。

InputStream和OutputStream的子类都是字节流 可以读写二进制文件,主要处理音频、图片、歌曲、字节流,处理单元 为1个字节。

Reader和Writer的子类都是字符流 主要处理字符或字符串,字符流处理单元为1个字符。 字节流将读取到的字节数据,去指定的编码表中获取对应文字。

字节流与字符流

字节流中常用类

字节输入流 FileInputStream

字节输出流 FileOutputStream

package com.ffyc.io.stream;

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

public class StreamDemo2 {


    public static void main(String[] args) throws IOException {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
             in =  new FileInputStream("E:/demo1.txt");
             out = new FileOutputStream("E:/demo2.txt");
             // in.read(); 一次读一个字节,返回字节编码(int), 文件内容读完后返回-1.
                int b = 0;
                while((b = in.read())!=-1){
                    out.write(b);
                    //write(int b); 一次向目标文件写出一个字节
                }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());//日志记录
        }finally {
               if(in!=null){
                   in.close();//关闭流通道 释放文件
               }
               if(out!=null){
                   out.close();
               }
        }

    }
}

字符流中常用类

字符输入流 FileReader

字符输出流 FileWriter

package com.ffyc.io.stream;

import java.io.*;

public class CharDemo {
    public static void main(String[] args) throws IOException {
       /*
        FileReader fileReader=new FileReader("E:\\ffyc\\练习/t1.txt");
        FileWriter fileWriter=new FileWriter("E:\\ffyc\\练习/t2.txt");
        BufferedReader bufferedReader=new BufferedReader(fileReader);
        BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
        int size=0;
        while ((size=bufferedReader.read())!=-1){
            bufferedWriter.write(size);
        }
        bufferedWriter.flush();
        bufferedReader.close();
        bufferedWriter.close();
        */
        FileReader fileReader=new FileReader("E:\\ffyc\\练习/t1.txt");
        FileWriter fileWriter=new FileWriter("E:\\ffyc\\练习/t3.txt",true);//追加,保留上一次文本文件。继续添加
        BufferedReader bufferedReader=new BufferedReader(fileReader);
        BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
        String s=null;
        char[] c=new char[5];
        int size=0;
        while ((size=bufferedReader.read(c))!=-1){
            bufferedWriter.write(c,0,size);
        }
        bufferedWriter.flush();
        bufferedReader.close();
        bufferedWriter.close();
    }
}

package com.ffyc.io.stream;

import java.io.Serializable;
/*
 Serializable 序列化接口
   如果需要将某个类的对象进行序列化,那么此类必须实现Serializable接口
    会为类生成一个版本号,如果不显得定义版本号,会自定默认生成,会有一个问题,每次当类改变了,版本号会重新生成
 */
public class Car implements Serializable {

    //序列化版本号 显示的定义之后,类信息发生改变不会重新生成
    private static final long serialVersionUID = -1981902868337741342L;

     //transient修饰的属性在序列式,不会保存到文件中
     private transient int no;
     private String name;


    public Car(int no, String name) {
        this.no = no;
        this.name = name;
    }

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

输入输出节点字节流

InputStream的基本方法

读取一个字节并以整数的形式返回(0~255),如果返回-1已到输入流的末尾。

int read() throws IOException

读取一系列字节并存储到一个数组buffer,返回实际读取的字节数,如果读取前已到输入流的末尾返回-1

int read(byte[] buffer) throws IOException

关闭流释放内存资源

void close() throws IOException

OutputStream的基本方法

向输出流中写入一个字节数据,该字节数据为参数b的低8位

void write(int b) throws IOException

将一个字节类型的数组中的从指定位置(off)开始的 len个字节写入到输出流

void write(byte[] b, int off, int len) throws IOException

关闭流释放内存资源

void close() throws IOException

package com.ffyc.io.stream;

import java.io.*;

public class ExeDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\ffyc\\Java\\2022-7-11_java第八章IO\\练习/feige.exe");
        exeFJ(file, 1024 * 1024);
        File file1 = new File("E:\\ffyc\\Java\\2022-7-11_java第八章IO\\练习/temp");
        exeHB(file1);

    }

    public static void exeFJ(File file, int n) throws IOException {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream("E:\\ffyc\\Java\\2022-7-11_java第八章IO\\练习/feige.exe");
            byte[] bytes = new byte[n];
            int size = 0;
            int i = 1;
            while ((size = inputStream.read(bytes)) != -1) {
                outputStream = new FileOutputStream("E:\\ffyc\\Java\\2022-7-11_java第八章IO\\练习/temp/" + i++ + ".temp");
                outputStream.write(bytes, 0, size);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }

    }

    public static void exeHB(File file) throws IOException {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        String[] s = file.list();
        try {
            outputStream = new FileOutputStream("E:\\ffyc\\Java\\2022-7-11_java第八章IO\\练习/temp/feige.exe");
            for (int i = 0; i < s.length; i++) {
                inputStream = new FileInputStream("E:\\ffyc\\Java\\2022-7-11_java第八章IO\\练习/temp/" + (i + 1) + ".temp");
                byte[] bytes = new byte[1024];
                int size = 0;
                while ((size = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, size);
                }
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }

        
    }
}

节点流与处理流

根据封装类型不同流又分为

节点流,处理流

节点流:

如果流封装的是某种特定的数据源,如文件、字符串、字符串数组等,则称为节点流。

处理流:

如果流封装的是其它流对象,称为处理流。 处理流提供了缓冲功能,提高读写效率,同时增加了一些新的方法。

节点流中常用类

字节输入流 FileInputStream

字节输出流 FileOutputStream

字符输入流 FileReader

字符输出流 FileWriter

处理流中常用类

缓冲字节输出流 BufferedOutputStream

缓冲字节输入流 BufferedInputStream

缓冲字符输入流 BufferedReader

缓冲字符输出流 BufferedWriter

package com.ffyc.io.stream;

import java.io.*;

public class BufferedStreamDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream in=new FileInputStream("E:\\ffyc\\练习/feige.exe");
        FileOutputStream out =new FileOutputStream("E:\\ffyc\\练习/fg.exe");
        BufferedInputStream bin=new BufferedInputStream(in);
        BufferedOutputStream bout=new BufferedOutputStream(out,2048);
        byte[]bytes=new byte[1024];
        int size=0;
        while ((size=bin.read(bytes))!=-1){
            bout.write(bytes);
        }
        bout.flush();
        bin.close();
        bout.close();
    }
}

输入输出节点字符流

Reader 的基本方法

读取一个字符并以整数的形式返回, 如果返回-1已到输入流的末尾。

int read() throws IOException

读取一系列字符并存储到一个数组buffer,返回实际读取的字符数,如果读取前已到输入流的末尾返回-1 。

int read( char[] cbuf) throws IOException

关闭void close() throws IOException

Writer 的基本方法

向输出流中写入一个字符数据,该字节数据为参数b的16位 。

void write(int c) throws IOException

一个字符类型的数组中的数据写入输出流 。

void write( char[] cbuf) throws IOException

将一个字符类型的数组中的从指定位置(off set)开始的 length个字符写入到输出流。

void write( char[] cbuf, int off set, int length) throws IOException

关闭void close() throws IOException

Print流

Print 打印流:

只做输出没有输入 打印流分为字节打印流和字符打印流。

PrintWriter:

字符打印流 print方法可以打印各种类型数据 。

在javaweb项目中,服务器端向客户端响应数据以打印流的方式响应.

package com.ffyc.io.stream;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class PrintDemo {

    public static void main(String[] args) throws FileNotFoundException {
        /*
            打印流:  单向的从程序中向目标输出数据
            PrintWriter 打印字符流
         */

         PrintWriter out =  new PrintWriter("E:/demo.html");
           out.print("<h1>你好客户端</h1>");
           out.print("<h1>你好客户端</h1>");
           out.print("<h1>你好客户端</h1>");
           out.print("<h1>你好客户端</h1>");
           out.close();
    }
}

对象输入输出流

对象的寿命通常随着生成该对象的程序的终止而终止。 有时候,可能需

要将对象的状态保存下来,在需要时再将对象恢复。

对象的输入输出流 :

主要的作用是用于写入对象信息与读取对象信息。 对象信息 一旦写到文

件上那么对象的信息就可以做到持久化了.

对象的输出流:ObjectOutputStream

对象的输入流:ObjectInputStream

在ObjectInputStream 中用readObject()方法可以直接读取一个对象,

ObjectOutputStream中用writeObject()方法可以直接将对象保存到输出流中。

对象的输出流将指定的对象写入到文件的过程,就是将对象序列化的过 程.

对象的输入流将指定序列化好的文件读出来的过程,就是对象反序列化的过程。

对象的输出流将对象写入到文件中称之为对象的序列化,所以被序列化 对象的类必须要实现 Serializable接口。 Serializable接口中没有任何 方法。当一个类声明实现Serializable接口后,表明该类可被序列化。

在类中可以生成一个编号

private static final long serialVersionUID = -5974713180104013488L;

随机生成 唯一的 serialVersionUID 用来表明实现序列化类的不同版本

间的兼容性。某个类在与之对应的对象已经序列化出去后做了修改,该

对象依然可以被正确反序列化.

如果不显示生成序列号,那么将会隐式生产,但是隐式生成后,类一旦发生

改变,序列号也会随之改变。
在这里插入图片描述

transient关键字

默认情况下当执行了对象序列化的时候会将类中的全部属性的内容进行全部的序列化操作,

但是很多情况下有一些属性可能并不需要序列化的处理,这个时候就可以在属性的定义上使

用transient关键字来完成了。

private transient String name;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值