cmsfileutil.java
来自「找了很久才找到到源代码」· Java 代码 · 共 796 行 · 第 1/2 页
JAVA
796 行
/*
* File : $Source: /usr/local/cvs/opencms/src/org/opencms/util/CmsFileUtil.java,v $
* Date : $Date: 2007-09-06 14:05:25 $
* Version: $Revision: 1.31 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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
*/
package org.opencms.util;
import org.opencms.configuration.CmsConfigurationManager;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.flex.CmsFlexCache;
import org.opencms.i18n.CmsEncoder;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsSystemInfo;
import org.opencms.staticexport.CmsLinkManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
/**
* Provides File utility functions.<p>
*
* @author Alexander Kandzior
*
* @version $Revision: 1.31 $
*
* @since 6.0.0
*/
public final class CmsFileUtil {
/**
* Hides the public constructor.<p>
*/
private CmsFileUtil() {
// empty
}
/**
* Adds a trailing separator to a path if required.<p>
*
* @param path the path to add the trailing separator to
* @return the path with a trailing separator
*/
public static String addTrailingSeparator(String path) {
int l = path.length();
if ((l == 0) || (path.charAt(l - 1) != '/')) {
return path.concat("/");
} else {
return path;
}
}
/**
* Checks if all resources are present.<p>
*
* @param cms an initialized OpenCms user context which must have read access to all resources
* @param resources a list of vfs resource names to check
*
* @throws CmsIllegalArgumentException in case not all resources exist or can be read with the given OpenCms user context
*/
public static void checkResources(CmsObject cms, List resources) throws CmsIllegalArgumentException {
StringBuffer result = new StringBuffer(128);
ListIterator it = resources.listIterator();
while (it.hasNext()) {
String resourcePath = (String)it.next();
try {
CmsResource resource = cms.readResource(resourcePath);
// append folder separator, if resource is a folder and does not and with a slash
if (resource.isFolder() && !resourcePath.endsWith("/")) {
it.set(resourcePath + "/");
}
} catch (CmsException e) {
result.append(resourcePath);
result.append('\n');
}
}
if (result.length() > 0) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_MISSING_RESOURCES_1,
result.toString()));
}
}
/**
* Simply version of a 1:1 binary file copy.<p>
*
* @param fromFile the name of the file to copy
* @param toFile the name of the target file
* @throws IOException if any IO error occurs during the copy operation
*/
public static void copy(String fromFile, String toFile) throws IOException {
File inputFile = new File(fromFile);
File outputFile = new File(toFile);
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile);
// transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
/**
* Returns the formatted filesize to Bytes, KB, MB or GB depending on the given value.<p>
*
* @param filesize in bytes
* @param locale the locale of the current OpenCms user or the System's default locale if the first choice
* is not at hand.
*
* @return the formatted filesize to Bytes, KB, MB or GB depending on the given value
**/
public static String formatFilesize(long filesize, Locale locale) {
String result;
filesize = Math.abs(filesize);
if (Math.abs(filesize) < 1024) {
result = Messages.get().getBundle(locale).key(Messages.GUI_FILEUTIL_FILESIZE_BYTES_1, new Long(filesize));
} else if (Math.abs(filesize) < 1048576) {
// 1048576 = 1024.0 * 1024.0
result = Messages.get().getBundle(locale).key(
Messages.GUI_FILEUTIL_FILESIZE_KBYTES_1,
new Double(filesize / 1024.0));
} else if (Math.abs(filesize) < 1073741824) {
// 1024.0^3 = 1073741824
result = Messages.get().getBundle(locale).key(
Messages.GUI_FILEUTIL_FILESIZE_MBYTES_1,
new Double(filesize / 1048576.0));
} else {
result = Messages.get().getBundle(locale).key(
Messages.GUI_FILEUTIL_FILESIZE_GBYTES_1,
new Double(filesize / 1073741824.0));
}
return result;
}
/**
* Returns a comma separated list of resource paths names, with the site root
* from the given OpenCms user context removed.<p>
*
* @param context the current users OpenCms context (optional, may be <code>null</code>)
* @param resources a List of <code>{@link CmsResource}</code> instances to get the names from
*
* @return a comma separated list of resource paths names
*/
public static String formatResourceNames(CmsRequestContext context, List resources) {
if (resources == null) {
return null;
}
StringBuffer result = new StringBuffer(128);
Iterator i = resources.iterator();
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
String path = res.getRootPath();
if (context != null) {
path = context.removeSiteRoot(path);
}
result.append(path);
if (i.hasNext()) {
result.append(", ");
}
}
return result.toString();
}
/**
* Returns the extension of the given resource name, that is the part behind the last '.' char,
* converted to lower case letters.<p>
*
* The extension of a file is the part of the name after the last dot, including the dot.
* The extension of a folder is empty.
* All extensions are returned as lower case<p>
*
* Please note: No check is performed to ensure the given file name is not <code>null</code>.<p>
*
* Examples:<br>
* <ul>
* <li><code>/folder.test/</code> has an empty extension.
* <li><code>/folder.test/config</code> has an empty extension.
* <li><code>/strange.filename.</code> has an empty extension.
* <li><code>/document.PDF</code> has the extension <code>.pdf</code>.
* </ul>
*
* @param resourceName the resource to get the extension for
*
* @return the extension of a resource
*/
public static String getExtension(String resourceName) {
// if the resource name indicates a folder
if (resourceName.charAt(resourceName.length() - 1) == '/') {
// folders have no extensions
return "";
}
// get just the name of the resource
String name = CmsResource.getName(resourceName);
// get the position of the last dot
int pos = name.lastIndexOf('.');
// if no dot or if no chars after the dot
if ((pos < 0) || ((pos + 1) == name.length())) {
return "";
}
// return the extension
return name.substring(pos).toLowerCase();
}
/**
* Returns the extension of the given file name, that is the part behind the last '.' char,
* converted to lower case letters.<p>
*
* The result does contain the '.' char. For example, if the input is <code>"opencms.html"</code>,
* then the result will be <code>".html"</code>.<p>
*
* If the given file name does not contain a '.' char, the empty String <code>""</code> is returned.<p>
*
* Please note: No check is performed to ensure the given file name is not <code>null</code>.<p>
*
* @param filename the file name to get the extension for
* @return the extension of the given file name
*
* @deprecated use {@link #getExtension(String)} instead, it is better implemented
*/
public static String getFileExtension(String filename) {
int pos = filename.lastIndexOf('.');
return (pos >= 0) ? filename.substring(pos).toLowerCase() : "";
}
/**
* Returns a list of all filtered files in the RFS.<p>
*
* If the <code>name</code> is not a folder the folder that contains the
* given file will be used instead.<p>
*
* Despite the filter may not accept folders, every subfolder is traversed
* if the <code>includeSubtree</code> parameter is set.<p>
*
* @param name a folder or file name
* @param filter a filter
* @param includeSubtree if to include subfolders
*
* @return a list of filtered <code>{@link File}</code> objects
*/
public static List getFiles(String name, FileFilter filter, boolean includeSubtree) {
List ret = new ArrayList();
File file = new File(name);
if (!file.isDirectory()) {
file = new File(file.getParent());
if (!file.isDirectory()) {
return ret;
}
}
File[] dirContent = file.listFiles();
for (int i = 0; i < dirContent.length; i++) {
File f = dirContent[i];
if (filter.accept(f)) {
ret.add(f);
}
if (includeSubtree && f.isDirectory()) {
ret.addAll(getFiles(f.getAbsolutePath(), filter, true));
}
}
return ret;
}
/**
* Returns the file name for a given VFS name that has to be written to a repository in the "real" file system,
* by appending the VFS root path to the given base repository path, also adding an
* folder for the "online" or "offline" project.<p>
*
* @param repository the base repository path
* @param vfspath the VFS root path to write to use
* @param online flag indicates if the result should be used for the online project (<code>true</code>) or not
*
* @return The full uri to the JSP
*/
public static String getRepositoryName(String repository, String vfspath, boolean online) {
StringBuffer result = new StringBuffer(64);
result.append(repository);
result.append(online ? CmsFlexCache.REPOSITORY_ONLINE : CmsFlexCache.REPOSITORY_OFFLINE);
result.append(vfspath);
return result.toString();
}
/**
* Creates unique, valid RFS name for the given filename that contains
* a coded version of the given parameters, with the given file extension appended.<p>
*
* This is used to create file names for the static export,
* or in a vfs disk cache.<p>
*
* @param filename the base file name
* @param extension the extension to use
* @param parameters the parameters to code in the result file name
*
* @return a unique, valid RFS name for the given parameters
*
* @see org.opencms.staticexport.CmsStaticExportManager
*/
public static String getRfsPath(String filename, String extension, String parameters) {
StringBuffer buf = new StringBuffer(128);
buf.append(filename);
buf.append('_');
int h = parameters.hashCode();
// ensure we do have a positive id value
buf.append(h > 0 ? h : -h);
buf.append(extension);
return buf.toString();
}
/**
* Normalizes a file path that might contain <code>'../'</code> or <code>'./'</code> or <code>'//'</code>
* elements to a normal absolute path, the path separator char used is {@link File#separatorChar}.<p>
*
* @param path the path to normalize
*
* @return the normalized path
*
* @see #normalizePath(String, char)
*/
public static String normalizePath(String path) {
return normalizePath(path, File.separatorChar);
}
/**
* Normalizes a file path that might contain <code>'../'</code> or <code>'./'</code> or <code>'//'</code>
* elements to a normal absolute path.<p>
*
* Can also handle Windows like path information containing a drive letter,
* like <code>C:\path\..\</code>.<p>
*
* @param path the path to normalize
* @param separatorChar the file separator char to use, for example {@link File#separatorChar}
*
* @return the normalized path
*/
public static String normalizePath(String path, char separatorChar) {
if (CmsStringUtil.isNotEmpty(path)) {
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?