• JAVA中的OutputStream输出流的用法
  • 发布于 2个月前
  • 202 热度
    0 评论
OutputStream 代表一个输出流,它也是一个抽象类,不能被实例化。OutputStream 定义了一些通用方法,如 write() 和 flush() 等,用于向输出流中写入数据。常用的 OutputStream 实现类包括:

1、FileOutputStream代码示例

文件输出流,用于向文件中写入数据。

import java.io.*;

public class FileOutputStreamExample {
        // 堆代码 duidaima.com
    public static void main(String[] args) {
        // 要写入的文件路径和名称
        String filePath = "C:/example/output.txt";
        // 要写入文件的内容
        String content = "Hello, World!";
        // 创建输出流对象
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(filePath);
            // 将字符串转换为字节数组,并将其写入文件
            fos.write(content.getBytes("UTF-8"));
            // 刷新输出流
            fos.flush();
            // 输出提示信息
            System.out.println("Content has been written to " + filePath);
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + filePath);
        } catch (IOException e) {
            System.out.println("Error writing file: " + e.getMessage());
        } finally {
            // 关闭输出流
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                System.out.println("Error closing file: " + e.getMessage());
            }
        }
    }
}

示例代码说明:
在示例中,我们首先指定要写入的文件路径和名称。在实际使用中,您应该将其替换为实际的文件路径和名称。
然后,我们创建一个用于写入文件的输出流对象。在创建FileOutputStream对象时,如果文件不存在,Java将会自动创建它。
接着,我们将要写入的内容转换为字节数组,并使用write()方法将其写入文件。
然后,我们使用flush()方法刷新输出流。在文件操作完成后,我们应该始终调用flush()方法以确保所有数据都被写入到磁盘上的文件中。
最后,我们关闭FileOutputStream对象,即使在发生异常时也应该关闭。

注意:在使用FileOutputStream类时,我们需要确保文件存在,并且我们有写入文件的权限。此外,在实际应用中,可能需要使用更高效的方法来写入大型文件,以避免IO开销的问题。


2、ByteArrayOutputStream代码示例:
字节数组输出流,用于将数据写入内存中的字节数组中。
import java.io.*;

public class ByteArrayOutputStreamExample {

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

        try {
            // 将字符串转换为字节数组,并写入到字节数组输出流中
            baos.write("Hello, World!".getBytes("UTF-8"));
            // 将字节数组输出流中的数据转换为字节数组
            byte[] bytes = baos.toByteArray();
            // 将字节数组转换为字符串,并输出到控制台
            String content = new String(bytes, "UTF-8");
            System.out.println(content);
        } catch (IOException e) {
            System.out.println("Error writing to byte array: " + e.getMessage());
        } finally {
            // 关闭字节数组输出流
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                System.out.println("Error closing byte array output stream: " + e.getMessage());
            }
        }
    }
}
示例代码说明:
在示例中,我们首先创建了一个ByteArrayOutputStream对象,用于向内存中的字节数组中写入数据。
然后,我们将要写入的内容转换为字节数组,并使用write()方法将其写入ByteArrayOutputStream对象。
接着,我们调用toByteArray()方法将ByteArrayOutputStream对象中的数据转换为字节数组。需要注意的是,要在调用toByteArray()方法之前先关闭ByteArrayOutputStream。
最后,我们将字节数组转换为字符串,并将其输出到控制台。

注意:在使用ByteArrayOutputStream类时,需要注意内存占用问题。BytesArrayOutputStream类主要用于在内存中临时存储数据。对于大数据,可能需要使用其他方式存储。


3、PipedOutputStream代码示例:
管道输出流,用于线程之间的通信。
import java.io.*;

public class PipedOutputStreamExample {

    public static void main(String[] args) {
        // 创建一对PipedInputStream和PipedOutputStream
        PipedInputStream input = new PipedInputStream();
        PipedOutputStream output = new PipedOutputStream();

        try {
            // 将输入流和输出流连接起来
            input.connect(output);

            // 创建一个写线程
            Thread writerThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 写入一些数据到PipedOutputStream
                        output.write("Hello, World!".getBytes("UTF-8"));
                        // 刷新PipedOutputStream
                        output.flush();
                        // 关闭PipedOutputStream
                        output.close();
                    } catch (IOException e) {
                        System.out.println("Error writing to pipe: " + e.getMessage());
                    }
                }
            });

            // 创建一个读线程
            Thread readerThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 读取PipedInputStream中的数据
                        byte[] buffer = new byte[1024];
                        int len = input.read(buffer);
                        // 将读取的字节转换为字符串,并输出到控制台
                        String content = new String(buffer, 0, len, "UTF-8");
                        System.out.println(content);
                        // 关闭PipedInputStream
                        input.close();
                    } catch (IOException e) {
                        System.out.println("Error reading from pipe: " + e.getMessage());
                    }
                }
            });

            // 启动写线程和读线程
            writerThread.start();
            readerThread.start();

            // 等待写线程和读线程完成
            writerThread.join();
            readerThread.join();
        } catch (IOException | InterruptedException e) {
            System.out.println("Error communicating between threads: " + e.getMessage());
        }
    }
}
示例代码说明:
在示例中,我们首先创建了一对PipedInputStream和PipedOutputStream,用于在线程之间进行通信。
接着,我们使用connect()方法将PipedInputStream和PipedOutputStream连接起来。
然后,我们创建一个写线程和一个读线程。在写线程中,我们向PipedOutputStream写入数据,并使用flush()和close()方法刷新和关闭输出流。在读线程中,我们从PipedInputStream读取数据,并将其转换为字符串并打印到控制台。在读操作完成后,我们关闭输入流

最后,我们启动写线程和读线程,并等待它们完成。


注意:在使用PipedInputStream和PipedOutputStream类时,需要考虑线程同步问题,以确保在线程之间正确地交换数据。在实际应用中,您可能需要使用更高级的同步机制来确保线程之间的协作。
用户评论