白骑士的Java教学Java核心类库 4.4 输入输出(I/O)

        欢迎来到Java核心类库的学习篇!在前面的章节中,我们探讨了字符串处理、常用数据结构和异常处理机制的相关知识。在本节中,我们将深入了解Java的输入输出(I/O)操作。I/O操作是指程序与外部环境之间的数据交换,包括从文件读取数据、向文件写入数据、从网络读取数据等。通过学习Java的I/O机制,你将掌握如何在Java程序中进行文件操作和数据流处理,这对于开发功能丰富的应用程序至关重要。

Java I/O的基本概念

        Java I/O系统提供了一组用于读写数据的类和接口,主要分为字节流(Byte Streams)和字符流(Character Streams)两类。

  • 字节流:处理字节数据,适用于所有类型的文件,如二进制文件、图片、音频文件等。主要类有‘InputStream‘和‘OutputStream‘及其子类。
  • 字符流:处理字符数据,适用于文本文件。主要类有‘Reader‘和‘Writer‘及其子类。

字节流

InputStream和OutputStream

        ‘InputStream‘和‘OutputStream‘是所有字节输入流和输出流的基类。

  • ‘InputStream‘:定义了读取字节的方法,如‘read()‘。
  • ‘OutputStream‘:定义了写入字节的方法,如‘write()‘。

        示例:

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


public class Main {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("input.txt");
             FileOutputStream fos = new FileOutputStream("output.txt")) {
            int byteData;
            while ((byteData = fis.read()) != -1) {

                fos.write(byteData);
            }
        } 

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

字符流

Reader和Writer

        ‘Reader‘和‘Writer‘是所有字符输入流和输出流的基类。

  • ‘Reader‘:定义了读取字符的方法,如‘read()‘。
  • ‘Writer‘:定义了写入字符的方法,如‘write()‘。

        示例:

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


public class Main {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("input.txt");
             FileWriter fw = new FileWriter("output.txt")) {
            int charData;

            while ((charData = fr.read()) != -1) {
                fw.write(charData);
            }
        } 

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

缓冲流

        缓冲流提供了对基本流的包装,增加了缓冲功能,提高了I/O操作的效率。

  • BufferedInputStream 和 BufferedOutputStream:用于字节流的缓冲。
  • BufferedReader 和 BufferedWriter:用于字符流的缓冲。

        示例:

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


public class Main {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
             BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
        } 

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

文件操作

        Java提供了‘File‘类用于操作文件和目录。

创建和删除文件

import java.io.File;
import java.io.IOException;


public class Main {
    public static void main(String[] args) {
        File file = new File("example.txt");
        try {
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } 
        
        else {
                System.out.println("File already exists.");
            }
        } 

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

        if (file.delete()) {
            System.out.println("File deleted: " + file.getName());
        } 

        else {
            System.out.println("Failed to delete the file.");
        }
    }
}

文件属性

import java.io.File;


public class Main {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.exists()) {
            System.out.println("File name: " + file.getName());
            System.out.println("Absolute path: " + file.getAbsolutePath());
            System.out.println("Writeable: " + file.canWrite());
            System.out.println("Readable: " + file.canRead());
            System.out.println("File size in bytes: " + file.length());
        } 

        else {
            System.out.println("The file does not exist.");
        }
    }
}

序列化

        序列化是将对象的状态转换为字节流,以便存储或传输。反序列化则是将字节流恢复为对象。Java通过‘Serializable‘接口和‘ObjectOutputStream‘、‘ObjectInputStream‘类实现序列化。

序列化示例

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


public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 30);

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            oos.writeObject(person);
        } 

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


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

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // getters and setters
}

反序列化示例

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


public class Main {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person person = (Person) ois.readObject();

            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
        } 

        catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}


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

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // getters and setters
}

总结

        在本篇博客中,我们详细介绍了Java的输入输出(I/O)机制。从基本的字节流和字符流,到提高效率的缓冲流,以及文件操作和对象序列化,通过这些知识的学习,你将能够在Java程序中进行各种I/O操作,处理文件和数据流。I/O操作是Java编程中非常重要的一部分,掌握这些技巧能够帮助你开发功能丰富且高效的应用程序。在接下来的学习中,我们将继续探讨Java核心类库中的其他重要内容,帮助你全面掌握Java编程技能。祝你学习愉快,不断进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白骑士所长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值