001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.core.io;
018
019import java.io.IOException;
020import java.io.OutputStream;
021import java.nio.channels.Channels;
022import java.nio.channels.WritableByteChannel;
023
024/**
025 * Extended interface for a resource that supports writing to it.
026 * Provides an {@link #getOutputStream() OutputStream accessor}.
027 *
028 * @author Juergen Hoeller
029 * @since 3.1
030 * @see java.io.OutputStream
031 */
032public interface WritableResource extends Resource {
033
034        /**
035         * Indicate whether the contents of this resource can be written
036         * via {@link #getOutputStream()}.
037         * <p>Will be {@code true} for typical resource descriptors;
038         * note that actual content writing may still fail when attempted.
039         * However, a value of {@code false} is a definitive indication
040         * that the resource content cannot be modified.
041         * @see #getOutputStream()
042         * @see #isReadable()
043         */
044        default boolean isWritable() {
045                return true;
046        }
047
048        /**
049         * Return an {@link OutputStream} for the underlying resource,
050         * allowing to (over-)write its content.
051         * @throws IOException if the stream could not be opened
052         * @see #getInputStream()
053         */
054        OutputStream getOutputStream() throws IOException;
055
056        /**
057         * Return a {@link WritableByteChannel}.
058         * <p>It is expected that each call creates a <i>fresh</i> channel.
059         * <p>The default implementation returns {@link Channels#newChannel(OutputStream)}
060         * with the result of {@link #getOutputStream()}.
061         * @return the byte channel for the underlying resource (must not be {@code null})
062         * @throws java.io.FileNotFoundException if the underlying resource doesn't exist
063         * @throws IOException if the content channel could not be opened
064         * @since 5.0
065         * @see #getOutputStream()
066         */
067        default WritableByteChannel writableChannel() throws IOException {
068                return Channels.newChannel(getOutputStream());
069        }
070
071}