Reading and writing text files

When reading and writing text files :
  • it is almost always a good idea to use buffering (default size is 8K)
  • it is often possible to use references to abstract base classes, instead of references to specific concrete classes
  • there is always a need to pay attention to exceptions (in particular, IOException and FileNotFoundException)
The close method :
  • always needs to be called, or else resources will leak
  • will automatically flush the stream, if necessary
  • calling close on a "wrapper" stream will automatically call close on its underlying stream
  • closing a stream a second time has no consequence
Commonly used items : The FileReader and FileWriter classes always use the system's default character encoding. If this default is not appropriate (for example, when reading an XML file which specifies its own encoding), the recommended alternatives are, for example :

FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader in = new InputStreamReader(fis, "UTF-8");

FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");

Scanner scanner = new Scanner(file, "UTF-8");

Example 1

This example uses JDK 1.5. To make it compatible with JDK 1.4, just change StringBuilder to StringBuffer:
  1. import java.io.*;

  2. public class ReadWriteTextFile {

  3.   /**
  4.   * Fetch the entire contents of a text file, and return it in a String.
  5.   * This style of implementation does not throw Exceptions to the caller.
  6.   *
  7.   * @param aFile is a file which already exists and can be read.
  8.   */
  9.   static public String getContents(File aFile) {
  10.     //...checks on aFile are elided
  11.     StringBuilder contents = new StringBuilder();
  12.     
  13.     try {
  14.       //use buffering, reading one line at a time
  15.       //FileReader always assumes default encoding is OK!
  16.       BufferedReader input =  new BufferedReader(new FileReader(aFile));
  17.       try {
  18.         String line = null//not declared within while loop
  19.         /*
  20.         * readLine is a bit quirky :
  21.         * it returns the content of a line MINUS the newline.
  22.         * it returns null only for the END of the stream.
  23.         * it returns an empty String if two newlines appear in a row.
  24.         */
  25.         while (( line = input.readLine()) != null){
  26.           contents.append(line);
  27.           contents.append(System.getProperty("line.separator"));
  28.         }
  29.       }
  30.       finally {
  31.         input.close();
  32.       }
  33.     }
  34.     catch (IOException ex){
  35.       ex.printStackTrace();
  36.     }
  37.     
  38.     return contents.toString();
  39.   }

  40.   /**
  41.   * Change the contents of text file in its entirety, overwriting any
  42.   * existing text.
  43.   *
  44.   * This style of implementation throws all exceptions to the caller.
  45.   *
  46.   * @param aFile is an existing file which can be written to.
  47.   * @throws IllegalArgumentException if param does not comply.
  48.   * @throws FileNotFoundException if the file does not exist.
  49.   * @throws IOException if problem encountered during write.
  50.   */
  51.   static public void setContents(File aFile, String aContents)
  52.                                  throws FileNotFoundException, IOException {
  53.     if (aFile == null) {
  54.       throw new IllegalArgumentException("File should not be null.");
  55.     }
  56.     if (!aFile.exists()) {
  57.       throw new FileNotFoundException ("File does not exist: " + aFile);
  58.     }
  59.     if (!aFile.isFile()) {
  60.       throw new IllegalArgumentException("Should not be a directory: " + aFile);
  61.     }
  62.     if (!aFile.canWrite()) {
  63.       throw new IllegalArgumentException("File cannot be written: " + aFile);
  64.     }

  65.     //use buffering
  66.     Writer output = new BufferedWriter(new FileWriter(aFile));
  67.     try {
  68.       //FileWriter always assumes default encoding is OK!
  69.       output.write( aContents );
  70.     }
  71.     finally {
  72.       output.close();
  73.     }
  74.   }

  75.   /** Simple test harness.   */
  76.   public static void main (String... aArguments) throws IOException {
  77.     File testFile = new File("C://Temp//blah.txt");
  78.     System.out.println("Original file contents: " + getContents(testFile));
  79.     setContents(testFile, "The content of this file has been overwritten...");
  80.     System.out.println("New file contents: " + getContents(testFile));
  81.   }

Example 2 This example demonstrates using Scanner to read a file line by line (it does not perform a write
operation) :
  1. import java.io.*;
  2. import java.util.Scanner;
  3. public final class ReadWithScanner {
  4.   public static void main(String... aArgs) throws FileNotFoundException {
  5.     ReadWithScanner parser = new ReadWithScanner("C://Temp//test.txt");
  6.     parser.processLineByLine();
  7.     log("Done.");
  8.   }
  9.   
  10.   /**
  11.   * @param aFileName full name of an existing, readable file.
  12.   */
  13.   public ReadWithScanner(String aFileName){
  14.     fFile = new File(aFileName);  
  15.   }
  16.   
  17.   /** Template method that calls {@link #processLine(String)}.  */
  18.   public final void processLineByLine() throws FileNotFoundException {
  19.     Scanner scanner = new Scanner(fFile);
  20.     try {
  21.       //first use a Scanner to get each line
  22.       while ( scanner.hasNextLine() ){
  23.         processLine( scanner.nextLine() );
  24.       }
  25.     }
  26.     finally {
  27.       //ensure the underlying stream is always closed
  28.       scanner.close();
  29.     }
  30.   }
  31.   
  32.   /** 
  33.   * Overridable method for processing lines in different ways.
  34.   *  
  35.   * <P>This simple default implementation expects simple name-value pairs, separated by an 
  36.   * '=' sign. Examples of valid input : 
  37.   * <tt>height = 167cm</tt>
  38.   * <tt>mass =  65kg</tt>
  39.   * <tt>disposition =  "grumpy"</tt>
  40.   * <tt>this is the name = this is the value</tt>
  41.   */
  42.   protected void processLine(String aLine){
  43.     //use a second Scanner to parse the content of each line 
  44.     Scanner scanner = new Scanner(aLine);
  45.     scanner.useDelimiter("=");
  46.     if ( scanner.hasNext() ){
  47.       String name = scanner.next();
  48.       String value = scanner.next();
  49.       log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
  50.     }
  51.     else {
  52.       log("Empty or invalid line. Unable to process.");
  53.     }
  54.     //(no need for finally here, since String is source)
  55.     scanner.close();
  56.   }
  57.   
  58.   // PRIVATE //
  59.   private final File fFile;
  60.   
  61.   private static void log(Object aObject){
  62.     System.out.println(String.valueOf(aObject));
  63.   }
  64.   
  65.   private String quote(String aText){
  66.     String QUOTE = "'";
  67.     return QUOTE + aText + QUOTE;
  68.   }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值