一个文本文件,命名为“javaio-appendfile.txt”,并包含以下内容。
ABC Hello追加新内容 new FileWriter(file,true)
 代码如下 复制代码 package .yiibai.file 结果
现在,文本文件“javaio-appendfile.txt”内容更新如下:
ABC Hello This content will append to the end of the file
二,BufferedWriter写入文件
缓冲字符(BufferedWriter )是一个字符流类来处理字符数据。不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符数据保存到文件。
 代码如下 复制代码 package .yiibai.iofile
 
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
 
public class WriteToFileExample {
 public static void main(String[] args) {
  try {
 
   String content = "This is the content to write into file"
 
   File file = new File("/users/mkyong/filename.txt")
 
   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile()
   }
 
   FileWriter fw = new FileWriter(file.getAbsoluteFile())
   BufferedWriter bw = new BufferedWriter(fw)
   bw.write(content)
   bw.close()
 
   System.out.println("Done")
 
  } catch (IOException e) {
   e.printStackTrace()
  }
 }
}
三,FileOutputStream写入文件
文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。请参阅下面的完整的例子。
package .yiibai.io
 
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
 
public class WriteFileExample {
 public static void main(String[] args) {
 
  FileOutputStream fop = null
  File file
  String content = "This is the text content"
 
  try {
 
   file = new File("c:/newfile.txt")
   fop = new FileOutputStream(file)
 
   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile()
   }
 
   // get the content in bytes
   byte[] contentInBytes = content.getBytes()
 
   fop.write(contentInBytes)
   fop.flush()
   fop.close()
 
   System.out.println("Done")
 
  } catch (IOException e) {
   e.printStackTrace()
  } finally {
   try {
    if (fop != null) {
     fop.close()
    }
   } catch (IOException e) {
    e.printStackTrace()
   }
  }
 }
}
更新的JDK7例如,.111.使用新的“尝试资源关闭”的方法来轻松处理文件。
package .yiibai.io
 
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
 
public class WriteFileExample {
 public static void main(String[] args) {
 
  File file = new File("c:/newfile.txt")
  String content = "This is the text content"
 
  try (FileOutputStream fop = new FileOutputStream(file)) {
 
   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile()
   }
 
   // get the content in bytes
   byte[] contentInBytes = content.getBytes()
 
   fop.write(contentInBytes)
   fop.flush()
   fop.close()
 
   System.out.println("Done")
 
  } catch (IOException e) {
   e.printStackTrace()
  }
 }
}