001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.io.output; 018 019import java.io.IOException; 020import java.io.Writer; 021 022/** 023 * Broken writer. This writer always throws an {@link IOException} from 024 * all {@link Writer} methods. 025 * <p> 026 * This class is mostly useful for testing error handling in code that uses a 027 * writer. 028 * 029 * @since 2.0 030 */ 031public class BrokenWriter extends Writer { 032 033 /** 034 * The exception that is thrown by all methods of this class. 035 */ 036 private final IOException exception; 037 038 /** 039 * Creates a new writer that always throws the given exception. 040 * 041 * @param exception the exception to be thrown 042 */ 043 public BrokenWriter(final IOException exception) { 044 this.exception = exception; 045 } 046 047 /** 048 * Creates a new writer that always throws an {@link IOException} 049 */ 050 public BrokenWriter() { 051 this(new IOException("Broken writer")); 052 } 053 054 /** 055 * Throws the configured exception. 056 * 057 * @param cbuf ignored 058 * @param off ignored 059 * @param len ignored 060 * @throws IOException always thrown 061 */ 062 @Override 063 public void write(final char[] cbuf, final int off, final int len) throws IOException { 064 throw exception; 065 } 066 067 /** 068 * Throws the configured exception. 069 * 070 * @throws IOException always thrown 071 */ 072 @Override 073 public void flush() throws IOException { 074 throw exception; 075 } 076 077 /** 078 * Throws the configured exception. 079 * 080 * @throws IOException always thrown 081 */ 082 @Override 083 public void close() throws IOException { 084 throw exception; 085 } 086 087}