⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ioutils.java

📁 水晶 ? ?  报表 ? ? ? 源码
💻 JAVA
字号:
/* ===================================================
 * JCommon : a free general purpose Java class library
 * ===================================================
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 * Project Lead:  David Gilbert (david.gilbert@object-refinery.com);
 *
 * (C) Copyright 2000-2003, by Object Refinery Limited and Contributors.
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * ------------
 * IOUtils.java
 * ------------
 * (C)opyright 2002, 2003, by Thomas Morgner and Contributors.
 *
 * Original Author:  Thomas Morgner;
 * Contributor(s):   David Gilbert (for Object Refinery Limited);
 *
 * $Id: IOUtils.java,v 1.4 2003/06/13 15:46:55 mungady Exp $
 *
 * Changes
 * -------
 * 26-Jan-2003 : Initial version
 * 23-Feb-2003 : Documentation
 * 25-Feb-2003 : Fixed Checkstyle issues (DG);
 * 29-Apr-2003 : Moved to jcommon
 */

package org.jfree.io;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

/**
 * The IOUtils provide some IO related helper methods.
 *
 * @author Thomas Morgner.
 */
public class IOUtils {

    /** the singleton instance of the utility package. */
    private static IOUtils instance;

    /**
     * DefaultConstructor.
     */
    protected IOUtils() {
    }

    /**
     * Gets the singleton instance of the utility package.
     *
     * @return the singleton instance.
     */
    public static IOUtils getInstance() {
        if (instance == null) {
            instance = new IOUtils();
        }
        return instance;
    }

    /**
     * Checks, whether the URL uses a file based protocol.
     *
     * @param url the url.
     * @return true, if the url is file based.
     */
    private boolean isFileStyleProtocol(URL url) {
        if (url.getProtocol().equals("http")) {
            return true;
        }
        if (url.getProtocol().equals("https")) {
            return true;
        }
        if (url.getProtocol().equals("ftp")) {
            return true;
        }
        if (url.getProtocol().equals("file")) {
            return true;
        }
        if (url.getProtocol().equals("jar")) {
            return true;
        }
        if (url.getProtocol().equals("http")) {
            return true;
        }
        return false;
    }

    /**
     * Parses the given name and returns the name elements as List of Strings.
     *
     * @param name the name, that should be parsed.
     * @return the parsed name.
     */
    private List parseName(String name) {
        ArrayList list = new ArrayList();
        StringTokenizer strTok = new StringTokenizer(name, "/");
        while (strTok.hasMoreElements()) {
            String s = (String) strTok.nextElement();
            if (s.length() != 0) {
                list.add(s);
            }
        }
        return list;
    }

    /**
     * Transforms the name list back into a single string, separated with "/".
     *
     * @param name the name list.
     * @return the constructed name.
     */
    private String formatName(List name) {
        StringBuffer b = new StringBuffer();
        Iterator it = name.iterator();
        while (it.hasNext()) {
            b.append(it.next());
            if (it.hasNext()) {
                b.append("/");
            }
        }
        return b.toString();
    }

    /**
     * Compares both name lists, and returns the last common index shared between
     * the two lists.
     *
     * @param baseName the name created using the base url.
     * @param urlName  the target url name.
     * @return the number of shared elements.
     */
    private int startsWithUntil(List baseName, List urlName) {
        int minIdx = Math.min(urlName.size(), baseName.size());
        for (int i = 0; i < minIdx; i++) {
            String baseToken = (String) baseName.get(i);
            String urlToken = (String) urlName.get(i);
            if (!baseToken.equals(urlToken)) {
                return i;
            }
        }
        return minIdx;
    }

    /**
     * Checks, whether the URL points to the same service. A service is equal
     * if the protocol, host and port are equal.
     *
     * @param url a url
     * @param baseUrl an other url, that should be compared.
     * @return true, if the urls point to the same host and port and use the same protocol,
     * false otherwise.
     */
    private boolean isSameService(URL url, URL baseUrl) {
        if (!url.getProtocol().equals(baseUrl.getProtocol())) {
            return false;
        }
        if (!url.getHost().equals(baseUrl.getHost())) {
            return false;
        }
        if (url.getPort() != baseUrl.getPort()) {
            return false;
        }
        return true;
    }

    /**
     * Creates a relative url by stripping the common parts of the the url.
     *
     * @param url the to be stripped url
     * @param baseURL the base url, to which the <code>url</code> is relative to.
     * @return the relative url, or the url unchanged, if there is no relation
     * beween both URLs.
     */
    public String createRelativeURL(URL url, URL baseURL) {
        if (isFileStyleProtocol(url) && isSameService(url, baseURL)) {
            ArrayList retval = new ArrayList();

            List urlName = parseName(url.getFile());
            List baseName = parseName(baseURL.getFile());
            int commonIndex = startsWithUntil(urlName, baseName);
            if (commonIndex == 0) {
                return url.toExternalForm();
            }

            if (url.equals(baseURL)) {
                return "";
            }

            if (commonIndex == urlName.size()) {
                // correct the base index if there is some weird mapping detected,
                // fi. the file url is fully included in the base url:
                //
                // base: /file/test/funnybase
                // file: /file/test
                //
                // this could be a valid configuration whereever virtual mappings are
                // allowed.
                commonIndex -= 1;
            }

            if (baseName.size() >= urlName.size()) {
                int levels = baseName.size() - commonIndex;
                for (int i = 0; i < levels; i++) {
                    retval.add("..");
                }
            }

            retval.addAll(urlName.subList(commonIndex, urlName.size()));
            return formatName(retval);
        }
        return url.toExternalForm();
    }

    /**
     * Copies the InputStream into the OutputStream, until the end of the stream
     * has been reached. This method uses a buffer of 4096 kbyte.
     *
     * @param in the inputstream from which to read.
     * @param out the outputstream where the data is written to.
     * @throws IOException if a IOError occurs.
     */
    public void copyStreams(InputStream in, OutputStream out)
        throws IOException {
        copyStreams(in, out, 4096);
    }

    /**
     * Copies the InputStream into the OutputStream, until the end of the stream
     * has been reached.
     *
     * @param in the inputstream from which to read.
     * @param out the outputstream where the data is written to.
     * @param buffersize the buffer size.
     * @throws IOException if a IOError occurs.
     */
    public void copyStreams(InputStream in, OutputStream out, int buffersize)
        throws IOException {
        // create a 4kbyte buffer to read the file
        byte[] bytes = new byte[buffersize];

        // the input stream does not supply accurate available() data
        // the zip entry does not know the size of the data
        while (in.available() != 0) {
            int bytesRead = in.read(bytes);
            if (bytesRead > -1) {
                out.write(bytes, 0, bytesRead);
            }
            else {
                // no more data...
                break;
            }
        }
    }

    /**
     * Copies the contents of the Reader into the Writer, until the end of the stream
     * has been reached. This method uses a buffer of 4096 kbyte.
     *
     * @param in the reader from which to read.
     * @param out the writer where the data is written to.
     * @throws IOException if a IOError occurs.
     */
    public void copyWriter(Reader in, Writer out)
        throws IOException {
        copyWriter(in, out, 4096);
    }

    /**
     * Copies the contents of the Reader into the Writer, until the end of the stream
     * has been reached.
     *
     * @param in  the reader from which to read.
     * @param out  the writer where the data is written to.
     * @param buffersize  the buffer size.
     *
     * @throws IOException if a IOError occurs.
     */
    public void copyWriter(Reader in, Writer out, int buffersize)
        throws IOException {
        // create a 4kbyte buffer to read the file
        char[] bytes = new char[buffersize];

        // the input stream does not supply accurate available() data
        // the zip entry does not know the size of the data
        int bytesRead = in.read(bytes);
        while (bytesRead > -1) {
            out.write(bytes, 0, bytesRead);
            bytesRead = in.read(bytes);
        }
    }

    /**
     * Extracts the file name from the URL.
     *
     * @param url the url.
     * @return the extracted filename.
     */
    public String getFileName(URL url) {
        String file = url.getFile();
        int last = file.lastIndexOf("/");
        if (last < 0) {
            return file;
        }
        return file.substring(last);
    }

    /**
     * Removes the file extension from the given file name.
     *
     * @param file the file name.
     * @return the file name without the file extension.
     */
    public String stripFileExtension(String file) {
        int idx = file.lastIndexOf(".");
        // handles unix hidden files and files without an extension.
        if (idx < 1) {
            return file;
        }
        return file.substring(0, idx);
    }

    /**
     * Checks, whether the child directory is a subdirectory of the base directory.
     *
     * @param base the base directory.
     * @param child the suspected child directory.
     * @return true, if the child is a subdirectory of the base directory.
     * @throws IOException if an IOError occured during the test.
     */
    public boolean isSubDirectory(File base, File child)
        throws IOException {
        base = base.getCanonicalFile();
        child = child.getCanonicalFile();

        File parentFile = child;
        while (parentFile != null) {
            if (base.equals(parentFile)) {
                return true;
            }
            parentFile = parentFile.getParentFile();
        }
        return false;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -