- 字节流转换为字节通道:
FileInputStream
和FileOutputStream
可以通过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();
}
}
- 字节通道转换为字节流:
FileChannel
没有直接转换为FileInputStream
或FileOutputStream
的方法,但可以通过PipedInputStream
和PipedOutputStream
间接实现。
- 示例代码:
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();
}
}