首页javatext_fileJava I/O - 如何使用新的Java IO将字符串写入文件

Java I/O - 如何使用新的Java IO将字符串写入文件

我们想知道如何使用新的Java IO将字符串写入文件。
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main{
  public static void main(String[] args) throws Exception{
    String phrase = new String("www.w3cschool.cn\n");

    File aFile = new File("test.txt");   
    FileOutputStream outputFile = null;  
    outputFile = new FileOutputStream(aFile, true);
    System.out.println("File stream created successfully.");

    FileChannel outChannel = outputFile.getChannel();
    
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("New buffer:           position = " + buf.position()
                       + "\tLimit = " + buf.limit() + "\tcapacity = "
                       + buf.capacity());
    // Load the data into the buffer
    for (char ch : phrase.toCharArray()) {
      buf.putChar(ch);
    }
    System.out.println("Buffer after loading: position = " + buf.position()
                       + "\tLimit = " + buf.limit() + "\tcapacity = "
                       + buf.capacity());
    buf.flip();
    System.out.println("Buffer after flip:    position = " + buf.position() 
                       + "\tLimit = " + buf.limit() + "\tcapacity = " 
                       + buf.capacity());

    outChannel.write(buf);
    outputFile.close();
    System.out.println("Buffer contents written to file.");
  }
}