首页javafilechannelJava I/O - 如何写一个字符串作为Bytes通过FileChannel

Java I/O - 如何写一个字符串作为Bytes通过FileChannel

我们想知道如何写一个字符串作为Bytes通过FileChannel。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class MainClass {
  public static void main(String[] args) {

    String phrase = new String("www.w3cschool.cn API \n");
    File aFile = new File("test.txt");

    FileOutputStream file = null;
    try {
      file = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    FileChannel outChannel = file.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(phrase.length());
    byte[] bytes = phrase.getBytes();
    buf.put(bytes);
    buf.flip();

    try {
      outChannel.write(buf);
      file.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}