Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2566545
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: 系统运维

2011-10-27 11:44:10

java写入文本文件代码
From:

  1. package net.chinaunix.blog.hzm.text;

  2. import java.io.FileWriter;
  3. import java.io.PrintWriter;
  4. import java.io.IOException;

  5. public class WriteFile {

  6.     private String path;
  7.     private boolean appendToFile = false;
  8.     
  9.     public WriteFile(String filePath){
  10.         path = filePath;
  11.     }
  12.     
  13.     public WriteFile(String filePath, boolean appendvalue){
  14.         path = filePath;
  15.         appendToFile = appendvalue;
  16.         
  17.     }
  18.     
  19.     public void writeToFile(String textLine) throws IOException{
  20.         
  21.         FileWriter writer = new FileWriter(path,appendToFile);
  22.         PrintWriter printer = new PrintWriter(writer);
  23.         printer.printf("%s"+"%n",textLine);
  24.         printer.close();
  25.         /*The %s between double quotes means a string of characters of any length.
  26.           The %n means a newline. So we're telling the printf method to format a      string  of characters and add a newline at the end.
  27.          */
  28.         
  29.     }
  30.     
  31. }

  1. package net.chinaunix.blog.hzm.text;

  2. import java.io.IOException;

  3. public class FileData {

  4.     public static void main(String[] args) throws IOException{
  5.         
  6.         String filePath = "C:/text.txt";
  7.         
  8.     
  9.         try{
  10.             WriteFile writer = new WriteFile(filePath,true);
  11.           &n bsp; writer.writeToFile("This is another line..");
  12.         }catch(IOException e){
  13.             System.out.println(e.getMessage());
  14.         }
  15.     }
  16. }
java.io.FileWriter

Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

java.io.PrintWriter

Unlike the class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking .

阅读(3569) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~