java IO

IO流

File类

File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)

File类声明在java.io包下

File类中并未涉及文件内容的操作,如果需要读取或者写入文件内容,必须使用IO流来完成

后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的“终点”

常用构造器

Public File (String pathname);以pathname为路径创造File对象,可以是绝对路径,也可以是相对路径,如果pathname是相对路径,则默认的当前路径在系统属性的user.dir中存储

*  File(String filename);
*  File(String parent,String child);
*  File(File parent,String child);
*  File(URI uri);
//构造器一
       File file = new File("hello.txt");
       //构造器二
       File file1 = new File("F:\\Developer\\javaCode" , "JavaSenior");

       //构造器三
       new File(file1 , "hi.txt");
       //注意:此时的文件只是在内存上存在,但是硬件上并没有实体文件

在这里插入图片描述

File类的常用方法

获取功能:

​ public String getAbsolutePath();获取绝对路径

​ Public String getPath();获取路径

​ Public String getName();获取文件名

​ Public String getParent();获取上层文件目录路径,若无,返回null

​ Public long length();获取文件长度(字节数)不能获取目录长度

​ public long lastModified();获取最后一次的修改时间,毫秒值

​ public String[] list();获取指定目录下所有文件或者文件目录的名称数组。

​ public File[] listFile(); 获取指定目录下的所有文件或文件目录的File数组。

命名功能

public boolean renameTo(File dest );把文件命名为指定的文件路径

        //public boolean renameTo(File dest );把文件命名为指定的文件路径
        File file = new File("hello.txt");
        File file1 = new File("F:\\Developer\\testDemo\\hi.txt");

        boolean rename = file.renameTo(file1);
        System.out.println(rename);
        //要想保证返回true,需要file在硬盘中是存在的,且file1不能存在
    }

判断功能

​ public boolean isDirectory(): 判断是否是文件目录

​ public boolean isFile() : 判断是否是文件
​ public boolean exists() : 判断是否存在
​ public boolean canRead() : 判断是否可读
​ public boolean canWrite() : 判断是否可写
​ public boolean isHidden() : 判断是否隐藏

File类的创建功能

​ public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
​ public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
​ public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
​ 注意事项:如果你创建文件或者 文件 目录没有 写 盘符路径 , 那么 , 默认在项目路径下

File类的删除功能

​ public boolean delete():删除文件或者文件夹
​ 删除注意事项:
​ Java中的删除不走 回收站。
​ 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录

//    public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
//    public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
//    public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
//    创建硬盘中对应的文件或文件目录

//    public boolean delete():删除文件或者文件夹
    @Test
    public void test2() throws IOException {

        //文件的创建
        File file =new File("hi.txt");
        if(!file.exists()){
            file.createNewFile();
            System.out.println("创建成功");
        }else{
           file.delete();
            System.out.println("删除成功" );
        }


    }

    @Test
    public void test3(){
        //文件目录的创建
        File newDiretory = new File("F:\\Developer\\testDemo\\io");
        boolean mkdir = newDiretory.mkdir();
        if (mkdir){
            System.out.println("创建成功");
        }

        File newDiretory1 = new File("F:\\Developer\\testDemo\\io\\io1");
        boolean mkdir1 = newDiretory1.mkdirs();
        if (mkdir1){
            System.out.println("创建成功");
        }
    }

IO流原理及流的分类

流的分类

按照操作的数据单位的不同分为:字节流和字符流

按照数据的流向不同分为:输入流,输出流

按照角色的不同分为:节点流、处理流

Java的IO流都是从如下4个抽象基类派生出来的

(抽象基类)字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter

IO流体系

在这里插入图片描述

其中只有FileInputStream、FileOutputStream、FileReader、FileWriter为节点流,其余全部是处理流

FileReader/FileWriter

FileReader
    /*
    将javaIO模块下的hello.txt文件的内容读入程序,并输出到控制台
     */
    @Test
    public void testFileReader(){
        FileReader fr = null;
        try {
            //1,首先要实例化File对象,指明要操作的文件
            //读入的文件一定要存在否则就会报文件不存在的异常
            File file = new File("hello.txt");
            //2、提供具体的流
            fr = new FileReader(file);

            //3、数据的读入
            //方式一
//        int data = fr.read();//read();返回一个字符,如果达到文件末尾,就返回-1
//        while (data != -1){
//            System.out.print((char) data);
//            data = fr.read();
//        }
            //方式二,对方式一的简化
            int data1;
            while ((data1 = fr.read()) != -1){
                System.out.print((char) data1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4、流的关闭操作
            try {
                if (fr != null){//防止因执行fr = new FileReader(file);失败执行fr.close();时的空指针异常
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //对read()操作的升级,使用read的重载方法
    @Test
    public void test2() {
        FileReader fr = null;
        try {
            //1,File类的实例化
            File file = new File("hello.txt");
            //2,FileReader流的实例化
            fr = new FileReader(file);
            //3,读入的操作
            char[] cbuf = new char[5];
            int len;


//            while ((len = fr.read(cbuf)) != -1){
//                for (int i = 0; i < cbuf.length; i++){
//                    System.out.println(cbuf[i]);
//                }
//            }
            //报错,当最后一次返回的字符个数小于数组的长度,则最后的本应该是
            //空的数组元素仍保留上一次返回的字符


            //read(char[] cbuf);返回每次读入cbuf数组中的字符个数,如果达到文件末尾,就返回-1
            while ((len = fr.read(cbuf)) != -1){
                //方式一
               for (int i = 0; i < len; i++){
                  System.out.print(cbuf[i]);
               }

               //方式二
//                String str = new String(cbuf);
//                System.out.println(str);
                //报错,同方式一

                //方式三,正确
                String str = new String(cbuf, 0, len);
                System.out.println(str);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null){
                try {
                    //4,资源的关闭
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

FileWriter
/*
    从内存中写出数据到硬盘的文件

    说明:
    1,输出造作指定的文件可以不存在,并不会包异常
        File对应的硬盘中的文件如果不存在,输出过程会自动穿件该文件
        File对应的硬盘中的文件如果存在,
            如果流使用的构造器是FileWriter(file, false)/FileWriter(file):对原有文件的覆盖,
            如果流使用的构造器是FileWriter(file, true);不会对源文件进行覆盖,而是在源文件的基础上
            堆加内容
    2,
     */
    public void testFileWriter() throws IOException {
        //1,File类的实例化,指明要写出的文件
        File file = new File("hello.txt");

        //2,提供FileWriter,用于文件的写出
        FileWriter fw = new FileWriter(file);

        //3,写出的具体操作
        fw.write("I hane a dream");


        //4,流资源的关闭
        fw.close();
    }

注意:不能用字符流处理图片等字节数据

FileInputStream/FileOutputStream

字节流处理中文可能会出现乱码,因为中文占三个字节,所以有可能一个中文字符不能一次全部读取,需要下一次读取剩余部分,所以会导致乱码

故对于文本文件(.txt \ .java \ .c \ .cpp),使用字符流处理

对于非文本文件(.jpg 、 .mp3 \ .mp4 \ .avi)使用字节流处理

@Test
    public void testFileInputStream() {
        FileInputStream fis = null;
        try {
            //字节流操作文本文件
            //1,造文件
            File file = new File("hello.txt");
            //造流
            fis = new FileInputStream(file);
            //读数据
            byte[] buffer = new byte[5];
            int len;
            while ((len = fis.read(buffer)) != -1){
                String str = new String(buffer,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
//字节流操作图片文件
    @Test
    public void testFileInputOutputStream()  {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcfile = new File("Picture.jpg");
            File destfile = new File("Picture1.jpg");

            //造流
            fis = new FileInputStream(srcfile);
            fos = new FileOutputStream(destfile);

            //读写过程
            byte[] buffer = new byte[5];
            int len;
            while ((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

缓冲流

作用:提升读取速度

原因:内部提供了一个缓冲区,每次将读取的文件内容存入缓冲区,而不是存入新的文件,当缓冲区满,或者读文件结束时将缓冲区内的内容一起存入新新文件

处理流就是套接在已有流的基础上

注:flush()刷新缓冲区

BufferedInputStream/BufferedOutputStream
 /*
    非文本文件的赋值
     */
    @Test
    public void BufferStreamTest(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //造文件
            File srcfile = new File("Picture.jpg");
            File destfile = new File("Picture1.jpg");

            //造节点流
            FileInputStream fis = new FileInputStream(srcfile);
            FileOutputStream fos = new FileOutputStream(destfile);

            //造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //复制的细节:读取,写入
            byte[] buffer = new byte[10];
            int len;
            while ((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源;先关闭外层的流,在关闭内层的流
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //我们在关闭完成时,内层流也会自动关闭,所以内层流可以不用单独关闭
//        fis.close();
//        fos.close();
        }
    }
BufferedReader/BufferedWrite
  /*
    使用BuffedReader和BufferedWriter实现文本的复制
     */
    @Test
    public void testBufferedReadWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(new File("Picture.jpg")));
            bw = new BufferedWriter(new FileWriter(new File("Picture1.jpg")));

            //读写操作
//            方式一
//            char[] cubf = new char[10];
//            int len;
//            while ((len =br.read(cubf)) != -1){
//                bw.write(cubf,0,len);
//            }

            //方式二
            //readLine():文件末尾返回null
            String data;
            while ((data = br.readLine()) != null){//data中不包含换行符
                //bw.write(data);这种方法文件是一行字符
                //方法一
                bw.write(data + "\n");

                //方法二
                bw.write(data);
                bw.newLine();//提供换行操作
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源关闭
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

转换流(属于字符流)

作用:提供了字节流与字符流之间的转换

分类

​ InputStreamReader;将InputStream转换为Reader

​ OutputStreamWriter:将OutputStream转换为Writer

字节流中的数据都是字符时,转成字符流操作更有效

很多时候我们用转换流来处理文件乱码问题,实现编码和解码功能

​ 解码:字节----->字符

​ 编码:字符----->字节

InputStreamReader/OutputStreamWriter

InputStreamReader:将字节的输入流转换为字符的输入流

 @Test
    public void test1(){
        InputStreamReader isr = null;
        try {
            FileInputStream fis = new FileInputStream("hello.txt");
//    InputStreamReader isr =new InputStreamReader(fis);使用 系统默认的字符集
            //参数2指明了字符集,具体使用哪个字符集,取决于文件存储时使用的字符集
            isr = new InputStreamReader(fis,"UTF-8");

            char[] cubf = new char[1024];
            int len;
            while ((len = isr.read(cubf)) != -1){
                String str = new String(cubf, 0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isr != null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

OutputStreamWriter:将字符的输出流转换为字节的输出流

拓展,字符编码

常见的编码表
 ASCII:美国标准信息交换码。
 用一个字节的7位可以表示。
 ISO8859-1:拉丁码表。欧洲码表
 用一个字节的8位表示。
 GB2312:中国的中文编码表。最多两个字节编码所有字符
 GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
 Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的
字符码。所有的文字都用两个字节来表示。
 UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。

标准输入、输出流

​ System.in和System.out分别代表了系统标准的输入和输出设备
​ 默认输入设备是:键盘,输出设备是:显示器
​ System.in的类型是InputStream
​ System.out的类型是PrintStream,其是OutputStream的子类
​ FilterOutputStream 的子类
​ 重定向:通过System类的setIn,setOut方法对默认设备进行改变。
​ public static void setIn(InputStream in)
​ public static void setOut(PrintStream out)

package JavaIOTest;
// MyInput.java: Contain the methods for reading int, double, float, boolean, short, byte and
// string values from the keyboard

import java.io.*;

public class MyInput {
    // Read a string from the keyboard
    public static String readString() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // Declare and initialize the string
        String string = "";

        // Get the string from the keyboard
        try {
            string = br.readLine();

        } catch (IOException ex) {
            System.out.println(ex);
        }

        // Return the string obtained from the keyboard
        return string;
    }

    // Read an int value from the keyboard
    public static int readInt() {
        return Integer.parseInt(readString());
    }

    // Read a double value from the keyboard
    public static double readDouble() {
        return Double.parseDouble(readString());
    }

    // Read a byte value from the keyboard
    public static double readByte() {
        return Byte.parseByte(readString());
    }

    // Read a short value from the keyboard
    public static double readShort() {
        return Short.parseShort(readString());
    }

    // Read a long value from the keyboard
    public static double readLong() {
        return Long.parseLong(readString());
    }

    // Read a float value from the keyboard
    public static double readFloat() {
        return Float.parseFloat(readString());
    }
}

/*
        从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续
    进行输入操作,直至当输入“e”或者“exit”时,退出程序。
     */
    @Test
    public void testLowToUper(){
        System.out.println("请输入信息(退出输入e或者exit):");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        try {
            while ((str = br.readLine()) != null){
                if ("e".equalsIgnoreCase(str) || "exit".equalsIgnoreCase(str)){
                    System.out.println("安全退出");
                    break;
                }
                System.out.println("--->" + str.toUpperCase());
                System.out.println("继续输入:");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

打印流

实现将 基本数据类型的数据格式转化为 字符串输出

打印流:PrintStream和PrintWriter
 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
 PrintStream和PrintWriter的输出不会抛出IOException异常
 PrintStream和PrintWriter有自动flush功能
 PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
 System.out返回的是PrintStream的实例

 /*
        打印流
     */
    @Test
    public void test(){
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
            ps = new PrintStream(fos, true);
            if (ps != null) {// 把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }
            for (int i = 0; i <= 255; i++) { // 输出ASCII字符
                System.out.print((char) i);
                if (i % 50 == 0) { // 每50个数据一行
                    System.out.println(); // 换行
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }
    }

数据流

为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
 DataInputStream 和 DataOutputStream
 在 分别“套接”在 InputStream 和 和 OutputStream 子 类的流 上
 DataInputStream 中的方法
boolean readBoolean() byte readByte()
char readChar() f loat readFloat()
double readDouble() short readShort()
long readLong() int readInt()
String readUTF() void readFully(byte[] b)
 DataOutputStream 中的方法
 将上述的方法的read改为相应的write即可。

对象流

ObjectInputStream 和OjbectOutputSteam
 用于存储和读取 基本数据类型数据或 对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
 序列化:用ObjectOutputStream类 保存基本类型数据或对象的机制
 反序列化:用ObjectInputStream类 读取基本类型数据或对象的机制
ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量

对象序列化

​ 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传
输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
​ 序列化的好处在于可将任何实现了Serializable接口的对象转化为 字节数据,使其在保存和传输时可被还原
​ 序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是JavaEE 平台的基础
​ 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。
否则,会抛出NotSerializableException异常
​ Serializable
​ Externalizable

凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
private static final long serialVersionUID;
serialVersionUID用来表明类的不同版本间的兼容性。 简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议,显式声明。
简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的
serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异
常。(InvalidCastException)

 /*
    序列化过程:将内的java对象存储到磁盘或通过网络传输出去
    使用ObjectOutputStream实现
     */
    @Test
    public void testObjectOtputStream(){
        ObjectOutputStream oos = null;
        try {
            //1、
            oos = new ObjectOutputStream(new FileOutputStream("Object.dat"));
            //2、
           oos.writeObject(new String("我爱北京天安门"));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                //3
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    反序列化,将磁盘文件里的对象还原为一个java对象
     */
    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("Object.dat"));

            Object object = ois.readObject();
            String str = (String)object;
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
自定义类的可序列化

要想一个对象时可序列化,需要满足如下条件

一、实现接口Serializable

二、凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:private static final long serialVersionUID;

三、必须让对象所属的类及其属性是可序列化的,(默认情况下,string和基本数据类型是序列化的。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值