自学内容网 自学内容网

Java之IO流详解

Java 的输入输出(IO)系统是 Java 编程的核心部分之一,用于处理数据的读写操作。Java 提供了一套强大的 API 来处理不同类型的 IO 操作,包括文件读写、网络传输、内存操作等。本文将深入介绍 Java 编程中的 IO,包括输入输出流、异常处理、数据格式等方面,并提供代码示例。

1. Java IO 的基本概念

Java IO 通过流(Stream)的概念进行数据的读写。流是一组有序的数据序列,从数据源流向数据目的地。Java IO 主要分为以下几种流:

1.1 输入流(Input Stream):

用于从数据源读取数据,如从文件中读取数据。

1.2 输出流(Output Stream):

用于向数据目的地写入数据,如向文件中写入数据。
根据数据的处理单位,流又可以分为字节流和字符流:

1.3 字节流:

以字节为单位进行读写。常用的字节流类有 FileInputStream 和 FileOutputStream。

1.4 字符流:

以字符为单位进行读写。常用的字符流类有 FileReader 和 FileWriter。

2. 字节流与字符流

2.1 字节流

字节流是 Java IO 中最基本的一种流,它可以处理任何类型的数据(如图片、音频、视频、文本等)。字节流主要通过 InputStream 和 OutputStream 这两个抽象类及其子类来实现。
FileInputStream 用于从文件中读取字节数据,FileOutputStream 用于向文件中写入字节数据。
示例代码:

import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
public class ByteStreamExample {  
    public static void main(String[] args) {  
        // 写入数据到文件  
        try (FileOutputStream fos = new FileOutputStream("output.txt")) {  
            fos.write("Hello, World!".getBytes());  
            fos.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        // 从文件中读取数据  
        try (FileInputStream fis = new FileInputStream("output.txt")) {  
            int bytesRead;  
            byte[] buffer = new byte[1024];  
            while ((bytesRead = fis.read(buffer)) != -1) {  
                System.out.print(new String(buffer, 0, bytesRead));  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

2.2 字符流

字符流专门用于处理文本数据,它以字符为单位进行读写,比字节流更适合处理文本文件。字符流主要通过 Reader 和 Writer 这两个抽象类及其子类来实现。
FileReader 用于从文件中读取字符数据,FileWriter 用于向文件中写入字符数据。
示例代码:

import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
  
public class CharacterStreamExample {  
    public static void main(String[] args) {  
        // 写入数据到文件  
        try (FileWriter fw = new FileWriter("output.txt")) {  
            fw.write("Hello, World!");  
            fw.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        // 从文件中读取数据  
        try (FileReader fr = new FileReader("output.txt")) {  
            int ch;  
            while ((ch = fr.read()) != -1) {  
                System.out.print((char) ch);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

3. 缓冲流

缓冲流是为了提高 IO 操作效率而引入的,它通过内部缓冲区来减少实际的 IO 操作次数。Java 提供了 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 BufferedStreamExample {  
    public static void main(String[] args) {  
        // 写入数据到文件  
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {  
            bw.write("Hello, World!");  
            bw.newLine();  
            bw.write("Buffered IO Example.");  
            bw.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        // 从文件中读取数据  
        try (BufferedReader br = new BufferedReader(new FileReader("output.txt"))) {  
            String line;  
            while ((line = br.readLine()) != null) {  
                System.out.println(line);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

4. 转换流

转换流用于在字节流和字符流之间进行转换。Java 提供了 InputStreamReader 和 OutputStreamWriter 这两个类来实现这种转换。
InputStreamReader:将字节输入流转换为字符输入流。
OutputStreamWriter:将字符输出流转换为字节输出流。
示例代码:

import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
import java.io.IOException;  
  
public class ConvertStreamExample {  
    public static void main(String[] args) {  
        // 写入数据到文件(字节流 -> 字符流)  
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8")) {  
            osw.write("Hello, World!");  
            osw.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        // 从文件中读取数据(字符流 -> 字节流)  
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream("output.txt"), "UTF-8")) {  
            int ch;  
            while ((ch = isr.read()) != -1) {  
                System.out.print((char) ch);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

5. 文件的操作

Java 提供了 File 类来表示和操作文件及目录。通过 File 类,可以获取文件的属性、创建和删除文件、遍历目录等。
示例代码:

import java.io.File;  
import java.io.IOException;  
  
public class FileOperationExample {  
    public static void main(String[] args) {  
        // 创建一个 File 对象  
        File file = new File("example.txt");  
  
        // 检查文件是否存在  
        if (!file.exists()) {  
            try {  
                // 创建一个新文件  
                file.createNewFile();  
                System.out.println("File created: " + file.getName());  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        } else {  
            System.out.println("File already exists.");  
        }  
  
        // 获取文件属性  
        System.out.println("File name: " + file.getName());  
        System.out.println("File path: " + file.getPath());  
        System.out.println("File absolute path: " + file.getAbsolutePath());  
        System.out.println("File size: " + file.length() + " bytes");  
  
        // 删除文件  
        if (file.delete()) {  
            System.out.println("File deleted: " + file.getName());  
        } else {  
            System.out.println("Failed to delete the file.");  
        }  
    }  
}

6. 异常处理

Java IO 操作中经常会遇到各种异常,如文件不存在、读写权限不足等。Java 通过异常处理机制来捕获和处理这些异常。常见的 IO 异常有 IOException 和 FileNotFoundException。
示例代码:

import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
  
public class ExceptionHandlingExample {  
    public static void main(String[] args) {  
        // 写入数据到文件  
        try (FileWriter fw = new FileWriter("output.txt")) {  
            fw.write("Hello, World!");  
            fw.flush();  
        } catch (IOException e) {  
            System.err.println("An error occurred while writing to the file:");  
            e.printStackTrace();  
        }  
  
        // 从文件中读取数据  
        try (FileReader fr = new FileReader("output.txt")) {  
            int ch;  
            while ((ch = fr.read()) != -1) {  
                System.out.print((char) ch);  
            }  
        } catch (IOException e) {  
            System.err.println("An error occurred while reading from the file:");  
            e.printStackTrace();  
        }  
    }  
}

原文地址:https://blog.csdn.net/qq_40921573/article/details/142833978

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!