Java高级特性:I/O流

目录

一、File类

二、Java流的分类

字节流

1、InputStream类常用方法

2、子类FileInputStream常用的构造方法

3、使用FileInputStream 读文本文件

4、 OutputStream类常用方法

5、子类FileOutputStream常用的构造方法

6、使用FileOutputStream 写文本文件

字符流

Read类

FileReader类

Writer类

FileWriter类

BufferedWriter类

读写二进制文件

使用 DataInputStream 读二进制文件

使用 DataOutputStream写二进制文件

序列化和反序列化

序列化实现步骤

反序列化实现步骤:


一、File类

1、在Java 中,File 类是 java.io 包中唯一代表磁盘文件本身的对象,也就是说,如果希望在程序中操作文件和目录,则都可以通过 File 类来完成。File 类定义了一些方法来操作文件,如新建、删除、重命名文件和目录等。
2、File 类不能访问文件内容本身,如果需要访问文件内容本身,则需要使用输入/输出流。
File 类提供了如下三种形式构造方法。

         1、File(String path):如果 path 是实际存在的路径,则该 File 对象表示的是目录;如果 path 是文件名,则该 File 对象表示的是文件。

        2、File(String path, String name):path 是路径名,name 是文件名。

        3、File(File dir, String name):dir 是路径对象,name 是文件名。

第一种:

File file1 = new File("D:\\helloworld.txt");

第二种:

File file2 = new File("D:\\","helloworld.txt");

第三种:

File file3 = new File("D:\\");
File file4 = new File(file3,"helloworld.txt");

File类的常用方法:

方法名说明
boolean exists

判断文件或目录是否存在

boolean isFile( )

判断是否是文件

boolean isDirectory( )

判断是否是目录

String getPath( )

返回此对象表示的文件的相对路径名

String getAbsolutePath( )

返回此对象表示的文件的绝对路径名

String getName( )

返回此对象表示的文件或目录的名称

boolean delete( )

删除此对象指定的文件或目录

boolean createNewFile( )

创建名称的空文件,不创建文件夹

long  length()

返回文件的长度,单位为字节, 如果文件不存在,则返回 0L

语法:boolean exists

File file = new File("D:\\");
System.out.println("目录是否存在:" + file.exists());
File helloFile = new File("D:\\helloworld.txt");
System.out.println("文件是否存在:" + helloFile.exists());

语法:boolean isFile( )

System.out.println("判断是否是文件" + helloFile.isFile());

语法:boolean isDirectory( )

System.out.println("判断是否是目录:" +helloFile.isDirectory());

语法:String getPath( )

 System.out.println("返回文件相对路径:" + helloFile.getPath());

语法:String getAbsolutePath( )

System.out.println("返回文件绝对路经:" + helloFile.getAbsolutePath());

语法:String getName( )

System.out.println("返回文件名称:" + helloFile.getName());

语法:boolean delete( )

System.out.println("是否删除成功:" + helloFile.delete());

语法:boolean createNewFile( )

File file1 = new File("D:\\helloworld.txt");
System.out.println("新文件是否创建成功:" + file1.createNewFile());

语法:long  length()

System.out.println("文件的长度" + file1.length() + "B");

二、Java流的分类

 

字节流是 8 位通用字节流,字符流是 16 位 Unicode 字符流 

字节流

1、InputStream类常用方法

int read( )

int read(byte[] b)

int read(byte[] b,int off,int len)

void close( )

int available():可以从输入流中读取的字节数目

2、子类FileInputStream常用的构造方法

FileInputStream(File file)

FileInputStream(String name) 

3、使用FileInputStream 读文本文件

1、引入相关的类

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

2、构造文件输入流

FileInputStream fis= new FileInputStream("c:\\test.txt");

3、读取文本文件的数据

fis.available(); 
fis.read();     

4、关闭文件流对象

 fis.close();

实例:

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

        FileInputStream fis = null;
        try {
            //创建输入流对象
            fis = new FileInputStream("F:\\JAVA\\hello.txt");

            System.out.println("可以从输入流中读取的字节数目是:" + fis.available());

            /*int data = fis.read();
            while (data != -1){
                System.out.print((char)data);
                data = fis.read();
            }*/
            //读取文件信息
            int data;
            while ((data = fis.read()) != -1){
                System.out.print((char)data);
            }
            System.out.println();
            System.out.println("文件读取完毕...");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(fis != null){
                    //关闭文件流对象
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4、 OutputStream类常用方法

void write(int c)

void write(byte[] buf)

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

void close()

void flush():强制把缓冲区的数据写到输出流中

5、子类FileOutputStream常用的构造方法

FileOutputStream (File file)

FileOutputStream(String name) 

FileOutputStream(String name,boolean append)

1.前两种构造方法在向文件写数据时将覆盖文件中原有的内容

2.创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件

6、使用FileOutputStream 写文本文件

1、引入相关文件

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

2、构造文件输出流

FileOutputStream fos = new FileOutputStream("text.txt");

3、把数据写入文本文件

String str ="好好学习Java";
byte[] words  = str.getBytes();
fos.write(words, 0, words.length); 

4、关闭文件流对象

 fos.close();

实例:

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

        FileOutputStream fos = null;

        try {
            //创建输出流对象
            fos = new FileOutputStream("F:\\JAVA\\study.txt",false);

            //写一个字符串
            String study = "GOOD GOOD STUDY, DAY DAY UP";

            //创建一个byte数组存放字符串
            byte[] bytes = study.getBytes();

            //把数据写入文件
            fos.write(bytes);

            System.out.println("内容写入完毕");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 字节流复制文件

public class Test {
    public static void main(String[] args) throws IOException {
        /**
         * 创建一个字节输入流对象,构造方法中绑定要读取的数据源
         * 创建一个字节输出流对象,构造方法中绑定要写入的目的地
         * 使用字节输入流对象中的方法read读取文件
         * 使用字节输出流对象中的方法write,把读取到的字节写入到目的地的文件中
         * 释放资源
         */
        //创建一个字节输入流对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("D:\\a.txt");
        //创建一个字节输出流对象,构造方法中绑定要写入的目的地
        FileOutputStream fos = new FileOutputStream("E:\\a.txt");
        //一次读取一个字节写入一个字节的方式
        //使用字节输入流对象中的方法read读取文件
        /*int len = 0;
        while ((len = fis.read()) != -1){
            //使用字节输出流对象中的方法write,把读取到的字节写入到目的地的文件中
            fos.write(len);
        }*/
        
        //使用数组缓存读取多个字节,写入多个字节
        byte[] bytes = new byte[1024];
        //使用字节输入流对象中的方法read读取文件
        int len = 0;
        while ((len = fis.read()) != 0){
            //使用字节输出流对象中的方法write,把读取到的字节写入到目的地的文件中
            fos.write(bytes,0,len);
        }
        
        //释放资源(先关写的,后关闭读的;如果写完了,肯定读完了)
        fos.close();
        fis.close();
    }
}

字符流

Read类

Reader类常用方法

int read( )

int read(char[] c)

read(char[] c,int off,int len)

void close( )

子类InputStreamReader常用的构造方法

InputStreamReader(InputStream in)

InputStreamReader(InputStream in,String charsetName)

FileReader类

FileReader类是InputStreamReader的子类

FileReader(File file)

FileReader(String name)

该类只能按照本地平台的字符编码来读取数据,用户不能指定其他的字符编码类型

System.out.println(System.getProperty("file.encoding"));  获得本地平台的字符编码类型

使用FileReader读取文件

1、引入相关的类

import java.io.Reader;
import java.io.FileReader;
Import java.io.IOExceprion;

2、创建FileReader对象

Reader fr= new FileReader("D:\\myDoc\\简介.txt");

3、读取文本文件的数据

fr.read(); 

4、关闭相关的流对象

fr.close();

实例:

public class ReaderTest {
    public static void main(String[] args) {
        Reader fr = null;
        try {
            fr = new FileReader("F:\\JAVA\\hello.txt");
            int data = -1;
            while ((data = fr.read())!=-1){
                System.out.print((char)data);
            }
            System.out.println();
            System.out.println("文件读取完毕...");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(fr!=null){
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

如何提高字符流读取文本文件的效率?使用FileReader类与BufferedReader

BufferedReader类是Reader类的子类

BufferedReader类带有缓冲区

按行读取内容的readLine()方法

BufferedReader常用的构造方法

BufferedReader(Reader in)

子类BufferedReader特有的方法

 readLine()

使用 BufferedReader读文本文件

1、引入相关的类

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

2、构造BufferReader对象和FileReader对象

Reader fr=
new  FileReader("C:\\myTest.txt "); 
BufferedReader br=new BufferedReader(fr); 

3、调用readLine()方法读取数据

br.readLine();

4、关闭文件流对象

br.close();
fr.close();

 实例:

public class BufferedReaderTest {
    public static void main(String[] args) {
        BufferedReader bfr = null;
        Reader fr = null;
        try{
            fr = new FileReader("F:\\JAVA\\copy.txt");

            bfr = new BufferedReader(fr);

            String line = null;
            while ((line = bfr.readLine())!=null){
                System.out.println(line);
            }

            System.out.println("文件内容读取完毕...");
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(bfr != null){
                    bfr.close();
                }

                if(fr != null){
                    fr.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

Writer类

Writer类常用方法

write(String str)

write(String str,int off,int len)

void close()v

oid flush()

子类OutputStreamWriter常用的构造方法

import java.io.Reader;
import java.io.FileWriter;
Import java.io.IOException;

OutputStreamWriter(OutputStream out)

OutputStreamWriter(OutputStream out,String charsetName)

FileWriter类

FileWriter类是OutputStreamWriter的子类

FileWriter (File file)

FileWriter (String name)

该类只能按照本地平台的字符编码来写数据,用户不能指定其他的字符编码类型

使用FileWriter写文件

1、引入相关的类

import java.io.Reader;
import java.io.FileWriter;
Import java.io.IOException;
fw.close(); 

2、创建FileReader对象

Writer fw= new FileWriter("D:\\myDoc\\简介.txt");

3、写文本文件

fw.write(); 

4、关闭相关的流对象

fw.close(); 

实例:

public class WriterTest {
    public static void main(String[] args) {
        Writer fw = null;
        try {
            fw = new FileWriter("F:\\JAVA\\writer.txt");
            String words = "你好世界";
            fw.write(words);
            System.out.println("内容写入文件完毕...");

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

BufferedWriter类

如何提高字符流写文本文件的效率?使用FileWriter类与BufferedWriter类

BufferedWriter类是Writer类的子类

BufferedWriter类带有缓冲区

BufferedWriter常用的构造方法

 BufferedWriter(Writer out)

使用 BufferedWriter写文件

1、引入相关的类

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

2、构造BufferReader对象和FileReader对象

FileWriter fw=new
FileWriter("C:\\myTest.txt"); 
BufferedWriter bw=new BufferedWriter(fw);

3、调用readLine()方法读取数据

bw.write("hello");

4、对象流的清空和关闭

bw.flush();  
fw.close();

实例:

public class BufferWriterTest {
    public static void main(String[] args) {
        Writer fw = null;
        BufferedWriter bw = null;

        try {
            fw = new FileWriter("F:\\JAVA\\buff.txt");
            bw = new BufferedWriter(fw);
            bw.write("fw = new FileWriter(\"buff.txt\");");
            bw.flush();

            System.out.println("内容写入到文本完毕...");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(bw != null){
                    bw.close();
                }

                if(fw!=null){
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

练习:替换文本文件内容

public class Work1 {
    public static void main(String[] args) {
        String words = "姓名:{name},品种:{type},主人是:{master}";
        String[] replaceWords = {"安培","柴犬","山上"};
        StringBuffer sbf = new StringBuffer(words);
        System.out.println("替换前:" + words);
        for (int i = 0;i<replaceWords.length;i++){
            int index = sbf.indexOf("{");
            if(index < 0){
                break;
            }
            int lastIndex = sbf.indexOf("}");
            sbf.replace(index,lastIndex+1,replaceWords[i]);
        }

        Writer fw = null;
        BufferedWriter bw = null;
        BufferedReader bfr = null;
        Reader fr = null;
        try {
            fw = new FileWriter("F:\\JAVA\\pet.txt");
            bw = new BufferedWriter(fw);
            bw.write(sbf.toString());
            bw.flush();

            System.out.println("内容写入到文本完毕...");

            fr = new FileReader("F:\\JAVA\\pet.txt");
            bfr = new BufferedReader(fr);

            String line = null;
            while ((line = bfr.readLine())!=null){
                System.out.println("替换后:" + line);
            }

            System.out.println("文件内容读取完毕...");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(bfr != null){
                    bfr.close();
                }

                if(fr != null){
                    fr.close();
                }

                if(bw != null){
                    bw.close();
                }

                if(fw!=null){
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

读写二进制文件

DataInputStream类

FileInputStream的子类

与FileInputStream类结合使用读取二进制文件

DataOutputStream类

FileOutputStream的子类

与FileOutputStream类结合使用写二进制文件

使用 DataInputStream 读二进制文件

1、引入相关内容

import java.io.FileInputStream; 
 import java.io.DataInputStream;

2、构造数据输入流对象

FileInputStream fis=new FileInputStream("C:\\HelloWorld.class");
DataInputStream dis=new DataInputStream(fis);

3、调用read()方法读取二进制数据

dis.read ();

4、关闭数据输入流

dis.close();

实例:

public class DataReadTest {
    public static void main(String[] args) {
        FileInputStream fis = null;
        DataInputStream dis = null;

        try {
            fis = new FileInputStream("F:\\JAVA\\hello.txt");
            dis = new DataInputStream(fis);

            int data = -1;
            while ((data = dis.read())!=-1){
                System.out.print((char)data);
            }

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

                if(fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用 DataOutputStream写二进制文件

1、引入相关内容

import java.io.FileOutputStream; 
import java.io.DataOutputStream;

2、构造数据输出流对象

FileOutputStream outFile=new FileOutputStream("C:\\temp.class");
DataOutputStream out=new DataOutputStream(outFile);

3、调用write()方法读取二进制数据

dis.write();

4、关闭数据输入流

out.close();

练习2:复制图片

public class ImgCopy {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;

        try {
            fis = new FileInputStream("F:\\JAVA\\kgc.png");
            dis = new DataInputStream(fis);

            fos = new FileOutputStream("F:\\JAVA\\bdqn.jpg");
            dos = new DataOutputStream(fos);

            byte[] bytes = new byte[dis.available()];
            int data = -1;
            while ((data=dis.read(bytes))!=-1){
                dos.write(bytes,0,data);
            }
            dos.flush();

            System.out.println("复制完毕...");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(dos != null){
                    dos.close();
                }

                if(fos != null){
                    fos.close();
                }

                if(dis != null){
                    dis.close();
                }

                if(fis!=null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

序列化和反序列化

序列化是将对象的状态写入到特定的流中的过程

反序列化则是从特定的流中获取数据重新构建对象的过程

序列化实现步骤

1、实现Serializable接口

2、创建对象输出流

3、调用writeObject()方法将对象写入文件

4、关闭对象输出流

实例:

先创建一个学生类

public class Student implements Serializable {
    private String name;
    private int age;
    private String gender;
    private String address;

    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;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Student(String name, int age, String gender, String address) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.address = address;
    }

    public Student(){}

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

 序列化:

public class SerializableObj {
    public static void main(String[] args) {
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;

        try {
            Student student = new Student("张三",19,"男","金水区");
            oos = new ObjectOutputStream(new FileOutputStream("F:\\JAVA\\student.txt"));
            oos.writeObject(student);
            oos.flush();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

反序列化实现步骤:

1、实现Serializable接口

2、创建对象输入流

3、调用readObject()方法将对象写入文件

4、关闭对象输入流

实例:

public class SerializableReadObj {
    public static void main(String[] args) {
        ObjectInputStream ois = null;

        try {
            ois = new ObjectInputStream(new FileInputStream("E:\\student.txt"));

            Student student = (Student)ois.readObject();

            System.out.println(student.toString());

            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值