使用 Channel 和 Buffer 编写文件
要使用 Channel 将数据写入文件,我们需要执行以下步骤:
- 首先,我们需要得到一个
FileOutputStream的对象 - 从
FileOutputStream获取FileChannel调用getChannel()方法 - 创建一个
ByteBuffer然后用数据填充它 - 然后我们必须调用
ByteBuffer的flip()方法并将其作为write()方法的参数传递给FileChannel - 完成写作后,我们必须关闭资源
import java.io.*;
import java.nio.*;
public class FileChannelWrite {
public static void main(String[] args) {
File outputFile = new File("hello.txt");
String text = "I love Bangladesh.";
try {
FileOutputStream fos = new FileOutputStream(outputFile);
FileChannel fileChannel = fos.getChannel();
byte[] bytes = text.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(bytes);
fileChannel.write(buffer);
fileChannel.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}