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     */
017    
018    package org.apache.commons.configuration;
019    
020    import java.io.File;
021    import java.io.FileInputStream;
022    import java.io.FileOutputStream;
023    import java.io.IOException;
024    import java.io.InputStream;
025    import java.io.OutputStream;
026    import java.net.URL;
027    import java.net.URLConnection;
028    import java.net.URLStreamHandler;
029    
030    /**
031     * A custom URLStreamHandler to test loading and saving configurations to non
032     * standard URLs. This handler acts like a file handler with write support.
033     *
034     * @author Emmanuel Bourg
035     * @version $Id: FileURLStreamHandler.java 1222450 2011-12-22 21:01:33Z oheger $
036     */
037    public class FileURLStreamHandler extends URLStreamHandler
038    {
039        @Override
040        protected URLConnection openConnection(URL u) throws IOException
041        {
042            final File file = new File(u.getFile());
043    
044            return new URLConnection(u) {
045    
046                @Override
047                public void connect() throws IOException
048                {
049                }
050    
051                @Override
052                public InputStream getInputStream() throws IOException
053                {
054                    return new FileInputStream(file);
055                }
056    
057                @Override
058                public OutputStream getOutputStream() throws IOException
059                {
060                    return new FileOutputStream(file);
061                }
062            };
063        }
064    }