Java/File Input Output/PrintWriter

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

A helper class for printing indented text

 
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.PrintWriter;
/**
 * A helper class for printing indented text
 *
 * @version $Revision: 1.2 $
 */
public class IndentPrinter {
    private int indentLevel;
    private String indent;
    private PrintWriter out;
    public IndentPrinter() {
        this(new PrintWriter(System.out), "  ");
    }
    public IndentPrinter(PrintWriter out) {
        this(out, "  ");
    }
    public IndentPrinter(PrintWriter out, String indent) {
        this.out = out;
        this.indent = indent;
    }
    public void println(Object value) {
        out.print(value.toString());
        out.println();
    }
    public void println(String text) {
        out.print(text);
        out.println();
    }
    public void print(String text) {
        out.print(text);
    }
    public void printIndent() {
        for (int i = 0; i < indentLevel; i++) {
            out.print(indent);
        }
    }
    public void println() {
        out.println();
    }
    public void incrementIndent() {
        ++indentLevel;
    }
    public void decrementIndent() {
        --indentLevel;
    }
    public int getIndentLevel() {
        return indentLevel;
    }
    public void setIndentLevel(int indentLevel) {
        this.indentLevel = indentLevel;
    }
    public void flush() {
        out.flush();
    }
}





A PrintWriter that also sends its output to a log stream

  
/*
 * 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);
}





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

  
/*
 * 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 <tt>PrintWriter</tt> that ends lines with a carriage return-line feed (<tt>CRLF</tt>).
 * 
 * <h3>Concurrency</h3>
 * This class is <b>as</b> synchronized as <tt>PrintWriter</tt>.
 * 
 * @version <tt>$Revision: 1958 $</tt>
 * @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();
    }
  }
}





Create PrintWriter from BufferedWriter

   

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
class MainClass {
  public static void main(String args[]) throws Exception {
    FileWriter fw = new FileWriter(args[0]);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw, false);

    pw.println(true);
    pw.println("A");
    pw.println(500);
    pw.println(40000L);
    pw.println(45.67f);
    pw.println(45.67);
    pw.println("Hello");
    pw.println(new Integer("99"));

    pw.close();
  }
}





Create PrintWriter from System.out

   
import java.io.PrintWriter;
class PrintWriterDemo {
  public static void main(String args[]) throws Exception {
    PrintWriter pw = new PrintWriter(System.out);
    // Experiment with some methods
    pw.println(true);
    pw.println("A");
    pw.println(500);
    pw.println(40000L);
    pw.println(45.67f);
    pw.println(45.67);
    pw.println("Hello");
    pw.println(new Integer("99"));
    // Close print writer
    pw.close();
  }
}





Create PrintWriter out of FileWriter

   
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
public class ListOfNumbers {
  private Vector<Integer> victor;
  private static final int SIZE = 10;
  public ListOfNumbers() {
    victor = new Vector<Integer>(SIZE);
    for (int i = 0; i < SIZE; i++)
      victor.addElement(new Integer(i));
  }
  public void writeList() {
    PrintWriter out = null;
    try {
      System.out.println("Entering try statement");
      out = new PrintWriter(new FileWriter("OutFile.txt"));
      for (int i = 0; i < SIZE; i++)
        out.println("Value at: " + i + " = " + victor.elementAt(i));
    } catch (ArrayIndexOutOfBoundsException e) {
      System.err.println("Caught ArrayIndexOutOfBoundsException: "
          + e.getMessage());
    } catch (IOException e) {
      System.err.println("Caught IOException: " + e.getMessage());
    } finally {
      if (out != null) {
        System.out.println("Closing PrintWriter");
        out.close();
      } else {
        System.out.println("PrintWriter not open");
      }
    }
  }
}





Write lines of text to file using a PrintWriter

   
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();
  }
}