开源中文网

您的位置: 首页 > 编程开发 > Java语言设计 > 正文

java写入文本文件代码

来源:  作者:

java写入文本文件代码

From:http://www.homeandlearn.co.uk/java/write_to_textfile.html
 

  1. package net.chinaunix.blog.hzm.text;
  2.  
  3. import java.io.FileWriter;
  4. import java.io.PrintWriter;
  5. import java.io.IOException;
  6.  
  7. public class WriteFile {
  8.  
  9.     private String path;
  10.     private boolean appendToFile = false;
  11.     
  12.     public WriteFile(String filePath){
  13.         path = filePath;
  14.     }
  15.     
  16.     public WriteFile(String filePath, boolean appendvalue){
  17.         path = filePath;
  18.         appendToFile = appendvalue;
  19.         
  20.     }
  21.     
  22.     public void writeToFile(String textLine) throws IOException{
  23.         
  24.         FileWriter writer = new FileWriter(path,appendToFile);
  25.         PrintWriter printer = new PrintWriter(writer);
  26.         printer.printf("%s"+"%n",textLine);
  27.         printer.close();
  28.         /*The %s between double quotes means a string of characters of any length.
  29.           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.
  30.          */
  31.         
  32.     }
  33.     
  34. }

  1. package net.chinaunix.blog.hzm.text;
  2.  
  3. import java.io.IOException;
  4.  
  5. public class FileData {
  6.  
  7.     public static void main(String[] args) throws IOException{
  8.         
  9.         String filePath = "C:/text.txt";
  10.         
  11.     
  12.         try{
  13.             WriteFile writer = new WriteFile(filePath,true);
  14.           &n bsp; writer.writeToFile("This is another line..");
  15.         }catch(IOException e){
  16.             System.out.println(e.getMessage());
  17.         }
  18.     }
  19. }
 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 PrintStream 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 checkError().

Tags:文本 代码 文件
关于开源中文网 - 联系我们 - 广告服务 - 网站地图 - 版权声明