001: /*
002: * Copyright (C) The Apache Software Foundation. All rights reserved.
003: *
004: * This software is published under the terms of the Apache Software License
005: * version 1.1, a copy of which has been included with this distribution in
006: * the LICENSE file.
007: */
008: package org.jivesoftware.util.log.output.io;
009:
010: import org.jivesoftware.util.log.format.Formatter;
011: import java.io.File;
012: import java.io.FileOutputStream;
013: import java.io.IOException;
014:
015: /**
016: * A basic target that writes to a File.
017: *
018: * @author <a href="mailto:peter@apache.org">Peter Donald</a>
019: */
020: public class FileTarget extends StreamTarget {
021:
022: ///File we are writing to
023: private File m_file;
024:
025: ///Flag indicating whether or not file should be appended to
026: private boolean m_append;
027:
028: /**
029: * Construct file target to send to a file with a formatter.
030: *
031: * @param file the file to send to
032: * @param append true if file is to be appended to, false otherwise
033: * @param formatter the Formatter
034: * @throws IOException if an error occurs
035: */
036: public FileTarget(final File file, final boolean append,
037: final Formatter formatter) throws IOException {
038: super (null, formatter);
039:
040: if (null != file) {
041: setFile(file, append);
042: openFile();
043: }
044: }
045:
046: /**
047: * Set the file for this target.
048: *
049: * @param file the file to send to
050: * @param append true if file is to be appended to, false otherwise
051: * @throws IOException if directories can not be created or file can not be opened
052: */
053: protected synchronized void setFile(final File file,
054: final boolean append) throws IOException {
055: if (null == file) {
056: throw new NullPointerException(
057: "file property must not be null");
058: }
059:
060: if (isOpen()) {
061: throw new IOException("target must be closed before "
062: + "file property can be set");
063: }
064:
065: m_append = append;
066: m_file = file;
067: }
068:
069: /**
070: * Open underlying file and allocate resources.
071: * This method will attempt to create directories below file and
072: * append to it if specified.
073: */
074: protected synchronized void openFile() throws IOException {
075: if (isOpen())
076: close();
077:
078: final File file = getFile().getCanonicalFile();
079:
080: final File parent = file.getParentFile();
081: if (null != parent && !parent.exists()) {
082: parent.mkdir();
083: }
084:
085: final FileOutputStream outputStream = new FileOutputStream(file
086: .getPath(), m_append);
087:
088: setOutputStream(outputStream);
089: open();
090: }
091:
092: /**
093: * Retrieve file associated with target.
094: * This allows subclasses to access file object.
095: *
096: * @return the output File
097: */
098: protected synchronized File getFile() {
099: return m_file;
100: }
101: }
|