Java 文件写操作

    在进行文件写操作的时候,有两种操作方方式。一个是连续写,一个是覆盖式写。

    代码如下:

  import java.io.BufferedWriter;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.OutputStreamWriter;

  // text:要写入的内容;isAppend:写入方式,true为连续写,false为覆盖式写入。

  public void write(String text, boolean isAppend) throws IOException {

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
       new FileOutputStream("D:/file.txt", isAppend)));
    bw.write(text);
    bw.flush();
    bw.close();
  }

  

  // FileOutputStream源码如下

  public FileOutputStream(String name, boolean append)

    throws FileNotFoundException {
    this(name != null ? new File(name) : null, append);
  }

  public FileOutputStream(File file, boolean append)
    throws FileNotFoundException {
    String name = (file != null ? file.getPath() : null);
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
      security.checkWrite(name);
    }
    if (name == null) {
      throw new NullPointerException();
    }
    fd = new FileDescriptor();
    fd.incrementAndGetUseCount();
    this.append = append;
    if (append) {
      openAppend(name);
    } else {
      open(name);
    }
  }

 

  /**
  * Opens a file, with the specified name, for appending.
  * @param name name of file to be opened
  */
  private native void openAppend(String name) throws FileNotFoundException;

  /**
  * Opens a file, with the specified name, for writing.
  * @param name name of file to be opened
  */
  private native void open(String name) throws FileNotFoundException;

 

posted @ 2014-08-21 23:07  Longzheyuan  阅读(214)  评论(0编辑  收藏  举报