Java Tutorial/File/PrintWriter

Материал из Java эксперт
Перейти к: навигация, поиск

A PrintWriter that also sends its output to a log stream

   <source lang="java">

/*

* Copyright 2005 Joe Walker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.BufferedWriter; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import org.apache.rumons.logging.LogFactory; import org.apache.rumons.logging.Log; /**

* A PrintWriter that also sends its output to a log stream
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/

public class DebuggingPrintWriter extends PrintWriter {

   /**
    * Create a new PrintWriter, without automatic line flushing.
    * @param prefix A tag to prefix lines with for debugging purposes
    * @param out A character-output stream
    */
   public DebuggingPrintWriter(String prefix, Writer out)
   {
       super(out, false);
       this.prefix = prefix;
   }
   /**
    * Create a new PrintWriter.
    * @param prefix A tag to prefix lines with for debugging purposes
    * @param out A character-output stream
    * @param autoFlush A boolean; if true, the println() methods will flush the output buffer
    */
   public DebuggingPrintWriter(String prefix, Writer out, boolean autoFlush)
   {
       super(out, autoFlush);
       this.prefix = prefix;
   }
   /**
    * Create a new PrintWriter, without automatic line flushing, from an
    * existing OutputStream.  This convenience constructor creates the
    * necessary intermediate OutputStreamWriter, which will convert characters
    * into bytes using the default character encoding.
    * @param prefix A tag to prefix lines with for debugging purposes
    * @param out An output stream
    * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
    */
   public DebuggingPrintWriter(String prefix, OutputStream out)
   {
       super(out, false);
       this.prefix = prefix;
   }
   /**
    * Create a new PrintWriter from an existing OutputStream.  This convenience
    * constructor creates the necessary intermediate OutputStreamWriter, which
    * will convert characters into bytes using the default character encoding.
    * @param prefix A tag to prefix lines with for debugging purposes
    * @param out An output stream
    * @param autoFlush A boolean; if true, the println() methods will flush the output buffer
    * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
    */
   public DebuggingPrintWriter(String prefix, OutputStream out, boolean autoFlush)
   {
       super(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);
       this.prefix = prefix;
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(boolean)
    */
   @Override
   public void print(boolean x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(char)
    */
   @Override
   public void print(char x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(int)
    */
   @Override
   public void print(int x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(long)
    */
   @Override
   public void print(long x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(float)
    */
   @Override
   public void print(float x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(double)
    */
   @Override
   public void print(double x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(char[])
    */
   @Override
   public void print(char[] x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(java.lang.String)
    */
   @Override
   public void print(String x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#print(java.lang.Object)
    */
   @Override
   public void print(Object x)
   {
       super.print(x);
       buffer.append(x);
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println()
    */
   @Override
   public void println()
   {
       synchronized (lock)
       {
           printBuffer();
           super.println();
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(boolean)
    */
   @Override
   public void println(boolean x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(char)
    */
   @Override
   public void println(char x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(int)
    */
   @Override
   public void println(int x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(long)
    */
   @Override
   public void println(long x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(float)
    */
   @Override
   public void println(float x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(double)
    */
   @Override
   public void println(double x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(char[])
    */
   @Override
   public void println(char[] x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(java.lang.String)
    */
   @Override
   public void println(String x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /* (non-Javadoc)
    * @see java.io.PrintWriter#println(java.lang.Object)
    */
   @Override
   public void println(Object x)
   {
       synchronized (lock)
       {
           printBuffer();
           super.println(x);
       }
   }
   /**
    * Write the characters in the print buffer out to the stream
    */
   private void printBuffer()
   {
       if (buffer.length() > 0)
       {
           log.debug(prefix + buffer.toString());
           buffer.setLength(0);
       }
   }
   /**
    * How to we prefix all the debugging lines?
    * @return the prefix
    */
   public String getPrefix()
   {
       return prefix;
   }
   /**
    * How to we prefix all the debugging lines?
    * @param prefix the prefix to set
    */
   public void setPrefix(String prefix)
   {
       this.prefix = prefix;
   }
   /**
    * How to we prefix all the debugging lines?
    */
   private String prefix;
   /**
    * A buffer where we store stuff before a newline
    */
   protected final StringBuffer buffer = new StringBuffer();
   /**
    * The log stream
    */
   private static final Log log = LogFactory.getLog(DebuggingPrintWriter.class);

}</source>





A PrintWriter that ends lines with a carriage return-line feed (CRLF).

   <source lang="java">

/*

* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; /**

* A PrintWriter that ends lines with a carriage return-line feed (CRLF).
* 
*

Concurrency

* This class is as synchronized as PrintWriter.
* 
* @version $Revision: 1958 $
* @author 
*/

public class CRLFPrintWriter extends PrintWriter {

 protected boolean autoFlush = false;
 public CRLFPrintWriter(final Writer out) {
   super(out);
 }
 public CRLFPrintWriter(final Writer out, final boolean autoFlush) {
   super(out, autoFlush);
   this.autoFlush = autoFlush;
 }
 public CRLFPrintWriter(final OutputStream out) {
   super(out);
 }
 public CRLFPrintWriter(final OutputStream out, final boolean autoFlush) {
   super(out, autoFlush);
   this.autoFlush = autoFlush;
 }
 protected void ensureOpen() throws IOException {
   if (out == null)
     throw new IOException("Stream closed");
 }
 public void println() {
   try {
     synchronized (lock) {
       ensureOpen();
       out.write("\r\n");
       if (autoFlush) {
         out.flush();
       }
     }
   } catch (InterruptedIOException e) {
     Thread.currentThread().interrupt();
   } catch (IOException e) {
     setError();
   }
 }

}</source>





PrintWriter

  1. PrintWriter is a better alternative to OutputStreamWriter and FileWriter.
  2. PrintWriter allows you to choose an encoding by passing the encoding information to one of its constructors.



   <source lang="java">

public PrintWriter (File file) public PrintWriter (File file, String characterSet) public PrintWriter (String filepath) public PrintWriter (String filepath, String ccharacterSet) public PrintWriter (OutputStream out) public PrintWriter (Writer out)</source>





PrintWriter is more convenient to work with than OutputStreamWriter

It adds nine print method overloads that allow you to output any type of Java primitives and objects.



   <source lang="java">

public void print (boolean b) public void print (char c) public void print (char[] s) public void print (double d) public void print (float f) public void print (int i) public void print (long l) public void print (Object object) public void print (String string)</source>



There are also nine println method overloads, which rint a new line character after printing the argument. In addition, there are two format method overloads that enable you to print according to a print format.


Turn System.out into a PrintWriter.

   <source lang="java">

import java.io.PrintWriter; public class MainClass {

 public static void main(String[] args) {
   PrintWriter out = new PrintWriter(System.out, true);
   out.println("Hello, world");
 }

}</source>





Using PrintWriter

   <source lang="java">

import java.io.IOException; import java.io.PrintWriter; public class MainClass {

 public static void main(String[] args) {
   try {
     PrintWriter pw = new PrintWriter("c:\\temp\\printWriterOutput.txt");
     pw.println("PrintWriter is easy to use.");
     pw.println(1234);
     pw.close();
   } catch (IOException e) {
   }
 }

}</source>





Write lines of text to file using a PrintWriter

   <source lang="java">

import java.io.FileWriter; import java.io.PrintWriter; public class Main {

 public static void main(String[] args) throws Exception {
   String filename = "fileName.txt";
   String[] linesToWrite = new String[] { "a", "b" };
   boolean appendToFile = true;
   PrintWriter pw = null;
   if (appendToFile) {
     pw = new PrintWriter(new FileWriter(filename, true));
   } else {
     pw = new PrintWriter(new FileWriter(filename));
     // pw = new PrintWriter(new FileWriter(filename, false));
   }
   for (int i = 0; i < linesToWrite.length; i++) {
     pw.println(linesToWrite[i]);
   }
   pw.flush();
   pw.close();
 }

}</source>