001    //$HeadURL: https://svn.wald.intevation.org/svn/deegree/base/branches/2.3_testing/src/org/deegree/framework/util/FileUtils.java $
002    /*----------------------------------------------------------------------------
003     This file is part of deegree, http://deegree.org/
004     Copyright (C) 2001-2009 by:
005       Department of Geography, University of Bonn
006     and
007       lat/lon GmbH
008    
009     This library is free software; you can redistribute it and/or modify it under
010     the terms of the GNU Lesser General Public License as published by the Free
011     Software Foundation; either version 2.1 of the License, or (at your option)
012     any later version.
013     This library is distributed in the hope that it will be useful, but WITHOUT
014     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
015     FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
016     details.
017     You should have received a copy of the GNU Lesser General Public License
018     along with this library; if not, write to the Free Software Foundation, Inc.,
019     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020    
021     Contact information:
022    
023     lat/lon GmbH
024     Aennchenstr. 19, 53177 Bonn
025     Germany
026     http://lat-lon.de/
027    
028     Department of Geography, University of Bonn
029     Prof. Dr. Klaus Greve
030     Postfach 1147, 53001 Bonn
031     Germany
032     http://www.geographie.uni-bonn.de/deegree/
033    
034     e-mail: info@deegree.org
035    ----------------------------------------------------------------------------*/
036    package org.deegree.framework.util;
037    
038    import java.io.BufferedReader;
039    import java.io.BufferedWriter;
040    import java.io.File;
041    import java.io.FileOutputStream;
042    import java.io.FileReader;
043    import java.io.FileWriter;
044    import java.io.IOException;
045    import java.io.InputStream;
046    import java.io.InputStreamReader;
047    import java.io.OutputStreamWriter;
048    import java.io.PrintWriter;
049    import java.io.RandomAccessFile;
050    import java.io.Reader;
051    import java.io.Writer;
052    import java.net.MalformedURLException;
053    import java.net.URL;
054    
055    /**
056     * the class offeres several static methods for handling file access
057     *
058     *
059     * @version $Revision: 18195 $
060     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
061     * @author last edited by: $Author: mschneider $
062     *
063     * @version 1.0. $Revision: 18195 $, $Date: 2009-06-18 17:55:39 +0200 (Do, 18. Jun 2009) $
064     *
065     * @since 2.0
066     */
067    public class FileUtils {
068    
069        /**
070         * writes the the passed string to a file created using the passed file name. For writing to the resource an
071         * <code>OutputStreamReader</code> with encoding read from <code>CharsetUtils.getSystemCharset()</code>.
072         *
073         * @param fileName
074         * @param data
075         * @throws IOException
076         */
077        public static final void writeToFile( String fileName, String data )
078                                throws IOException {
079            writeToFile( fileName, data, CharsetUtils.getSystemCharset() );
080        }
081    
082        /**
083         * writes the the passed string to a file created using the passed file name using the defined character encoding.
084         *
085         * @param fileName
086         * @param data
087         * @param encoding
088         * @throws IOException
089         */
090        public static final void writeToFile( String fileName, String data, String encoding )
091                                throws IOException {
092            FileOutputStream fos = new FileOutputStream( fileName );
093            OutputStreamWriter osr = new OutputStreamWriter( fos, encoding );
094            osr.write( data );
095            osr.close();
096        }
097    
098        /**
099         * appends the passed string to the file identified by the passed name. If the file does not exist an exception will
100         * be thrown.
101         *
102         * @param fileName
103         * @param data
104         * @throws IOException
105         */
106        public static final void appendsToFile( String fileName, String data )
107                                throws IOException {
108            File file = new File( fileName );
109            if ( !file.exists() ) {
110                throw new IOException( "file: " + fileName + " does not exist" );
111            }
112            RandomAccessFile raf = new RandomAccessFile( file, "rw" );
113            raf.seek( raf.length() );
114            raf.writeChars( data );
115            raf.close();
116        }
117    
118        /**
119         * reads a Text file from its resource. For accessing the resource an <code>InputStreamReader</code> with encoding
120         * read from <code>CharsetUtils.getSystemCharset()</code>
121         *
122         * @param file
123         * @return contents of the file as a {@link StringBuffer}
124         * @throws IOException
125         */
126        public static StringBuffer readTextFile( File file )
127                                throws IOException {
128            return readTextFile( file.toURL() );
129        }
130    
131        /**
132         * reads a Text file from its resource. For accessing the resource an <code>InputStreamReader</code> with encoding
133         * read from <code>CharsetUtils.getSystemCharset()</code>
134         *
135         * @param url
136         * @return contents of the url as a {@link StringBuffer}
137         * @throws IOException
138         */
139        public static StringBuffer readTextFile( URL url )
140                                throws IOException {
141            return readTextFile( url.openStream() );
142        }
143    
144        /**
145         * reads a Text file from its resource. For accessing the resource an <code>InputStreamReader</code> with encoding
146         * read from <code>CharsetUtils.getSystemCharset()</code>
147         *
148         * @param is
149         * @return contents of the input stream as a {@link StringBuffer}
150         * @throws IOException
151         */
152        public static StringBuffer readTextFile( InputStream is )
153                                throws IOException {
154            InputStreamReader isr = new InputStreamReader( is, CharsetUtils.getSystemCharset() );
155            return readTextFile( isr );
156        }
157    
158        /**
159         * reads a Text file from its resource.
160         *
161         * @param reader
162         * @return contents of the reader as a {@link StringBuffer}
163         * @throws IOException
164         */
165        public static StringBuffer readTextFile( Reader reader )
166                                throws IOException {
167            StringBuffer sb = new StringBuffer( 10000 );
168            int c = 0;
169            while ( ( c = reader.read() ) > -1 ) {
170                sb.append( (char) c );
171            }
172            reader.close();
173    
174            return sb;
175        }
176    
177        /**
178         * copies a file to another
179         *
180         * @param from
181         * @param to
182         * @throws IOException
183         */
184        public static void copy( File from, File to )
185                                throws IOException {
186            RandomAccessFile rafIn = new RandomAccessFile( from, "r" );
187            RandomAccessFile rafOut = new RandomAccessFile( to, "rw" );
188            byte[] b = new byte[500000];
189            int r = 0;
190            do {
191                r = rafIn.read( b );
192                if ( r > 0 ) {
193                    rafOut.write( b, 0, r );
194                }
195            } while ( r == b.length );
196            rafIn.close();
197            rafOut.close();
198        }
199    
200        /**
201         * @param oldRegex
202         * @param replacement
203         * @param inFile
204         *            file.encoding encoded text file
205         * @param outFile
206         *            file.encoding encoded text file
207         * @throws IOException
208         */
209        public static void replace( String oldRegex, String replacement, File inFile, File outFile )
210                                throws IOException {
211            replace( oldRegex, replacement, new BufferedReader( new FileReader( inFile ) ),
212                     new BufferedWriter( new FileWriter( outFile ) ) );
213        }
214    
215        /**
216         * Closes the streams!
217         *
218         * @param oldRegex
219         * @param replacement
220         * @param reader
221         * @param writer
222         * @throws IOException
223         */
224        public static void replace( String oldRegex, String replacement, Reader reader, Writer writer )
225                                throws IOException {
226            BufferedReader in = new BufferedReader( reader );
227            PrintWriter out = new PrintWriter( writer );
228            String s;
229            while ( ( s = in.readLine() ) != null ) {
230                out.println( s.replaceAll( oldRegex, replacement ) );
231            }
232            in.close();
233            out.close();
234        }
235    
236        /**
237         *
238         * Resolves the given URL (which may be relative) against a rootPath into an <code>URL</code> (which is always
239         * absolute).
240         *
241         * @param rootPath
242         * @param url
243         * @return the resolved URL object
244         */
245        public static final URL resolt( URL rootPath, String url )
246                                throws MalformedURLException {
247            // check if url is an absolut path
248            File file = new File( url );
249            if ( file.isAbsolute() ) {
250                return file.toURI().toURL();
251            }
252            // remove leading '/' because otherwise
253            // URL resolvedURL = new URL( systemId, url ); will fail
254            if ( url.startsWith( "/" ) ) {
255                url = url.substring( 1, url.length() );
256    
257            }
258            return new URL( rootPath, url );
259        }
260    
261    }