要使用通道(Channel )将数据写入文件,我们需要执行下面的步骤:
- 首先,我们需要获取fileoutputstream的对象
- 从FileOutputStream中获取FileChannel调用getChannel()方法
- 创建一个ByteBuffer,然后用数据填写它
- 然后我们必须调用ByteBuffer的触发器()方法,并将其传递为FileChannel的Write()方法的参数
- 写完后,我们必须关闭资源
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 apple.";
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();
}
}
}
日期:2020-06-02 22:15:23 来源:oir作者:oir
