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 * </p> 029 * 030 * @since 2.0 031 */ 032public class BrokenWriter extends Writer { 033 034 /** 035 * The exception that is thrown by all methods of this class. 036 */ 037 private final IOException exception; 038 039 /** 040 * Creates a new writer that always throws the given exception. 041 * 042 * @param exception the exception to be thrown 043 */ 044 public BrokenWriter(final IOException exception) { 045 this.exception = exception; 046 } 047 048 /** 049 * Creates a new writer that always throws an {@link IOException} 050 */ 051 public BrokenWriter() { 052 this(new IOException("Broken writer")); 053 } 054 055 /** 056 * Throws the configured exception. 057 * 058 * @param cbuf ignored 059 * @param off ignored 060 * @param len ignored 061 * @throws IOException always thrown 062 */ 063 @Override 064 public void write(final char[] cbuf, final int off, final int len) throws IOException { 065 throw exception; 066 } 067 068 /** 069 * Throws the configured exception. 070 * 071 * @throws IOException always thrown 072 */ 073 @Override 074 public void flush() throws IOException { 075 throw exception; 076 } 077 078 /** 079 * Throws the configured exception. 080 * 081 * @throws IOException always thrown 082 */ 083 @Override 084 public void close() throws IOException { 085 throw exception; 086 } 087 088}