Java 函数库中都有哪些常用 I/O 数据流工具?

java 函数库中的 i/o 数据流工具主要包括:inputstream:抽象输入流outputstream:抽象输出流fileinputstream:从文件读取字节fileoutputstream:向文件写入字节bytearrayinputstream:从字节数组读取字节bytearrayoutputstream:向字节数组写入字节bufferedinputstream:带缓冲区的输入流,提高性能bufferedoutputstream:带缓冲区的输出流,提高性能datainputstream:从输入流读取基本数据类型dataoutputstream:向输出流写入基本数据类型

Java 函数库中都有哪些常用 I/O 数据流工具?

Java 函数库中的常用 I/O 数据流工具

简介

数据流工具在 Java 中用来处理二进制数据,在输入/输出 (I/O) 操作中非常有用。Java 函数库提供了多个 I/O 数据流工具,本文将介绍最常用的工具,并提供实战案例。

常用数据流工具

工具描述
InputStream抽象输入流
OutputStream抽象输出流
FileInputStream从文件读取字节
FileOutputStream向文件写入字节
ByteArrayInputStream从字节数组读取字节
ByteArrayOutputStream向字节数组写入字节
BufferedInputStream带缓冲区的输入流,提高性能
BufferedOutputStream带缓冲区的输出流,提高性能
DataInputStream从输入流读取基本数据类型
DataOutputStream向输出流写入基本数据类型

实战案例

读取文本文件

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

public class ReadTextFile {

    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("myfile.txt")) {
            // 逐字节读取文件
            int c;
            while ((c = fis.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
登录后复制

写入文本文件

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

public class WriteTextFile {

    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("myfile.txt")) {
            // 写入文本
            String text = "Hello, world!";
            fos.write(text.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
登录后复制

从字节数组读取基本数据类型

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class ReadBasicTypesFromBytes {

    public static void main(String[] args) {
        // 定义字节数组并写入基本数据类型
        byte[] bytes = {1, 2, 3, 4};
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        DataInputStream dis = new DataInputStream(bis);

        try {
            // 读取基本数据类型
            int i = dis.readInt();
            System.out.println("Int: " + i);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
登录后复制

向字节数组写入基本数据类型

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class WriteBasicTypesToBytes {

    public static void main(String[] args) {
        // 创建字节数组输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        try {
            // 写入基本数据类型
            dos.writeInt(12345);
            dos.flush();
            // 获取字节数组
            byte[] bytes = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
登录后复制

以上就是Java 函数库中都有哪些常用 I/O 数据流工具?的详细内容,更多请关注小编网其它相关文章!

转载请说明出处 内容投诉内容投诉
南趣百科 » Java 函数库中都有哪些常用 I/O 数据流工具?

南趣百科分享生活经验知识,是您实用的生活科普指南。

查看演示 官网购买