import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelExample { public static void main(String[] args) throws Exception { String data = "Hello, World!"; FileOutputStream outputStream = new FileOutputStream("output.txt"); FileChannel channel = outputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put(data.getBytes()); buffer.flip(); channel.write(buffer); outputStream.close(); channel.close(); } }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; public class FileChannelExample { public static void main(String[] args) throws Exception { File inputFile = new File("input.txt"); File outputFile = new File("output.txt"); FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); FileChannel inputChannel = inputStream.getChannel(); FileChannel outputChannel = outputStream.getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); inputChannel.transferTo(0, inputChannel.size(), outputChannel); inputStream.close(); inputChannel.close(); outputStream.close(); outputChannel.close(); } }Description: In the above example, we created a file input stream to read data from the input file and a file output stream to write data to the output file. We then obtained file channel objects for both the input stream and output stream. We then transferred data from the input file channel to the output file channel using the file channels' `transferFrom()` and `transferTo()` methods. Finally, we closed the input stream, input channel, output stream, and output channel. Package Library: java.io