MST

星途 面试题库

面试题:Java中NIO通道与流如何相互转换

请阐述在Java NIO中,字节通道(如FileChannel)与字节流(如FileInputStream、FileOutputStream)相互转换的具体方法,并给出简单代码示例。
30.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 字节流转换为字节通道
    • FileInputStreamFileOutputStream可以通过getChannel()方法转换为对应的FileChannel
    • 示例代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class StreamToChannelExample {
    public static void main(String[] args) throws Exception {
        // 将FileInputStream转换为FileChannel
        FileInputStream fis = new FileInputStream("input.txt");
        FileChannel inputChannel = fis.getChannel();

        // 将FileOutputStream转换为FileChannel
        FileOutputStream fos = new FileOutputStream("output.txt");
        FileChannel outputChannel = fos.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (inputChannel.read(buffer) != -1) {
            buffer.flip();
            outputChannel.write(buffer);
            buffer.clear();
        }

        inputChannel.close();
        outputChannel.close();
        fis.close();
        fos.close();
    }
}
  1. 字节通道转换为字节流
    • FileChannel没有直接转换为FileInputStreamFileOutputStream的方法,但可以通过PipedInputStreamPipedOutputStream间接实现。
    • 示例代码:
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChannelToStreamExample {
    public static void main(String[] args) throws Exception {
        FileChannel fileChannel = FileChannel.open(java.nio.file.Paths.get("input.txt"), StandardOpenOption.READ);
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            try {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while (fileChannel.read(buffer) != -1) {
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        pos.write(buffer.get());
                    }
                    buffer.clear();
                }
                pos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        int data;
        while ((data = pis.read()) != -1) {
            System.out.print((char) data);
        }
        pis.close();
        fileChannel.close();
        executor.shutdown();
    }
}