下面列出了org.apache.commons.io.FilenameUtils#separatorsToUnix ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 上传文件
* <p>
* 该方法与{@link #uploadAndLogout(String, String, String, String, InputStream)}的区别是:
* 上传完文件后没有登出服务器及释放连接,但会关闭输入流;
* 之所以提供该方法是用于同时上传多个文件的情况下,使之能够共用一个FTP连接
* </p>
* @param hostname 目标主机地址
* @param username FTP登录用户
* @param password FTP登录密码
* @param remoteURL 保存在FTP上的含完整路径和后缀的完整文件名
* @param is 文件输入流
* @return True if successfully completed, false if not.
*/
public static boolean upload(String hostname, String username, String password, String remoteURL, InputStream is){
if(!login(hostname, username, password, DEFAULT_DEFAULT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, DEFAULT_DATA_TIMEOUT)){
return false;
}
FTPClient ftpClient = ftpClientMap.get();
try{
remoteURL = FilenameUtils.separatorsToUnix(remoteURL);
if(!ftpClient.changeWorkingDirectory(FilenameUtils.getFullPathNoEndSeparator(remoteURL))){
createRemoteFolder(ftpClient, FilenameUtils.getFullPathNoEndSeparator(remoteURL));
ftpClient.changeWorkingDirectory(FilenameUtils.getFullPathNoEndSeparator(remoteURL));
}
String remoteFile = new String(FilenameUtils.getName(remoteURL).getBytes(DEFAULT_CHARSET), "ISO-8859-1");
ftpClient.setCopyStreamListener(new FTPProcess(is.available(), System.currentTimeMillis()));
return ftpClient.storeFile(remoteFile, is);
}catch(IOException e){
LogUtil.getLogger().error("文件["+remoteURL+"]上传到FTP服务器["+hostname+"]失败,堆栈轨迹如下", e);
return false;
}finally{
IOUtils.closeQuietly(is);
}
}
/**
* 获取文档中待杂凑文件流
*
* @return 文件信息流
*/
private List<ToDigestFileInfo> toBeDigestFileList() throws IOException {
List<ToDigestFileInfo> res = new LinkedList<>();
// 获取OFD容器在文件系统中的路径
Path containerPath = ofdDir.getContainerPath();
// 文件系统中的容器Unix类型绝对路径,如:"/home/root/tmp"
String sysRoot = FilenameUtils.separatorsToUnix(containerPath.toAbsolutePath().toString());
// 遍历OFD文件目录中的所有文件
Files.walkFileTree(containerPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
// 路径转换为Unix类型的绝对路径
String abxFilePath = FilenameUtils.separatorsToUnix(file.toAbsolutePath().toString());
// 替换文件系统的根路径,这样就为容器系统中的绝对路径
abxFilePath = abxFilePath.replace(sysRoot, "");
// 如果采用继续签章模式,那么跳过对 Signatures.xml 的文件
if (signMode == SignMode.ContinueSign
&& abxFilePath.equals(signaturesLoc.getLoc())) {
return FileVisitResult.CONTINUE;
}
// 构造加入文件信息列表
res.add(new ToDigestFileInfo(abxFilePath, file));
return FileVisitResult.CONTINUE;
}
});
return res;
}
private Ignore(IFile virtualFile) {
file = virtualFile;
stringPath = FilenameUtils.separatorsToUnix(virtualFile.getPath());
Flog.debug("Initializing ignores for %s", file);
for (IFile vf : file.getChildren()) {
addRules(vf);
}
}
@Override
protected File valueOf(String text) {
if (text == null) {
return null;
}
return new File(FilenameUtils.separatorsToUnix(text));
}
@Override
public void put(File source, String destination)
throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
if ( source.isDirectory() ) {
throw new IllegalArgumentException( "Source is a directory: " + source );
}
String resourceName = FilenameUtils.separatorsToUnix(destination);
Resource resource = new Resource(resourceName);
firePutInitiated(resource, source);
firePutStarted(resource, source);
try {
File file = new File(checkoutDirectory, destination);
file.getParentFile().mkdirs();
transfer(resource, source, new FileOutputStream(file), true);
} catch (Exception e) {
fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
throw new TransferFailedException("Unable to put file", e);
}
firePutCompleted(resource, source);
}
protected static String replaceNameInPath(int pathItemIndexFromEnd, final String path, final String newName) {
int foldersInNewName = numberOfFolders(newName);
final String normalizedSeparators = FilenameUtils.separatorsToUnix(path);
int start = normalizedSeparators.length();
while (start >= 0 && pathItemIndexFromEnd >= 0) {
start = normalizedSeparators.lastIndexOf('/', start - 1);
pathItemIndexFromEnd--;
}
String result = path;
if (start >= 0) {
final int indexEnd = normalizedSeparators.indexOf('/', start + 1);
while (start >= 0 && foldersInNewName > 0) {
start = normalizedSeparators.lastIndexOf('/', start - 1);
foldersInNewName--;
}
if (start >= 0) {
if (indexEnd <= 0) {
result = path.substring(0, start + 1) + newName;
}
else {
result = path.substring(0, start + 1) + newName + path.substring(indexEnd);
}
}
}
return result;
}
public Boolean isIgnored(IFile f, String relPath) {
if (isFlooIgnored(f, f.getPath())) {
Flog.log("Ignoring %s just because.", f.getPath());
return true;
}
relPath = FilenameUtils.separatorsToUnix(relPath);
return !relPath.equals(stringPath) && isGitIgnored(relPath, f.isDirectory());
}
public void makeWorkingDir(File repoFolder) throws IOException {
repoFolder.mkdirs();
repoFolder.mkdir();
File dbDir = new File(repoFolder, "db");
FileUtils.forceMkdir(dbDir);
// build phisically the working directory
// and change settings config
String docDir = FilenameUtils.separatorsToUnix(repoFolder.getPath() + "/docs/");
FileUtils.forceMkdir(new File(docDir));
String indexDir = FilenameUtils.separatorsToUnix(repoFolder.getPath() + "/index/");
FileUtils.forceMkdir(new File(indexDir));
String userDir = FilenameUtils.separatorsToUnix(repoFolder.getPath() + "/users/");
FileUtils.forceMkdir(new File(userDir));
String pluginDir = FilenameUtils.separatorsToUnix(repoFolder.getPath() + "/plugins/");
FileUtils.forceMkdir(new File(pluginDir));
String importDir = FilenameUtils.separatorsToUnix(repoFolder.getPath() + "/impex/in/");
FileUtils.forceMkdir(new File(importDir));
String exportDir = FilenameUtils.separatorsToUnix(repoFolder.getPath() + "/impex/out/");
FileUtils.forceMkdir(new File(exportDir));
String logDir = FilenameUtils.separatorsToUnix(repoFolder.getPath() + "/logs/");
FileUtils.forceMkdir(new File(logDir));
String dbDirectory = FilenameUtils.separatorsToSystem(repoFolder.getPath() + "/db/");
ContextProperties pbean = Context.get().getProperties();
pbean.setProperty("store.1.dir", docDir);
pbean.setProperty("store.write", "1");
pbean.setProperty("index.dir", indexDir);
pbean.setProperty("conf.userdir", userDir);
pbean.setProperty("conf.plugindir", pluginDir);
pbean.setProperty("conf.importdir", importDir);
pbean.setProperty("conf.exportdir", exportDir);
pbean.setProperty("conf.logdir", logDir);
pbean.setProperty("conf.dbdir", dbDirectory);
pbean.write();
// Refresh the current logging location
try {
String log4jPath = URLDecoder.decode(this.getClass().getResource("/log.xml").getPath(), "UTF-8");
System.err.println("log4jPath = " + log4jPath);
Log4jConfigurer.initLogging(log4jPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
reloadContext();
}
private String buildPath(String path, String file) {
return StringUtils.isEmpty(path) ? file : FilenameUtils.separatorsToUnix(FilenameUtils.concat(path, file));
}
private String getSrcFilePath(ZipEntry entry) {
String parent = new File(srcFile).getParent();
return FilenameUtils.separatorsToUnix(new File(parent, entry.getName()).getPath());
}
public WildcardScanner(File rootPath, String pattern) {
this.rootPath = rootPath;
this.pattern = FilenameUtils.separatorsToUnix(pattern);
}
public void method() {
FilenameUtils.separatorsToUnix("my/unix/filename");
ToStringBuilder.reflectionToString(new Person("name"));
new GrowthList();
new PersonList().doSomethingWithImpl(); // compile with api-spi, runtime with api
}
/**
* Converts a path to a class file (like "foo/bar/My.class" or "foo\\bar\\My.class") to a fully qualified class name
* (like "foo.bar.My").
*/
public static String classFilePathToClassname(String relativePath)
{
if (relativePath == null)
return null;
final int pos = relativePath.lastIndexOf(".class");
if (pos < 0 && relativePath.lastIndexOf(".java") < 0)
throw new IllegalArgumentException("Not a .class/.java file path: " + relativePath);
relativePath = FilenameUtils.separatorsToUnix(relativePath);
if (relativePath.startsWith("/"))
{
relativePath = relativePath.substring(1);
}
if (relativePath.startsWith("src/main/java/"))
{
relativePath = relativePath.substring("src/main/java/".length());
}
if (relativePath.startsWith("WEB-INF/classes/"))
{
relativePath = relativePath.substring("WEB-INF/classes/".length());
}
if (relativePath.startsWith("WEB-INF/classes.jdk15/"))
{
relativePath = relativePath.substring("WEB-INF/classes.jdk15/".length());
}
if (relativePath.endsWith(".class"))
{
relativePath = relativePath.substring(0, relativePath.length() - ".class".length());
}
else if (relativePath.endsWith(".java"))
{
relativePath = relativePath.substring(0, relativePath.length() - ".java".length());
}
String qualifiedName = relativePath.replace("/", ".");
return qualifiedName;
}
public static QualifiedName createPersistentPropertyQualifiedName(String base, String postfix) {
return new QualifiedName(XdsCorePlugin.PLUGIN_ID + "." + base, FilenameUtils.separatorsToUnix(postfix));
}
public void method() {
FilenameUtils.separatorsToUnix("my/unix/filename");
ToStringBuilder.reflectionToString(new Person("name"));
new GrowthList();
new PersonList().doSomethingWithImpl(); // compile with api-spi, runtime with api
}
CompassV2(File path, Map<String, Object> options) {
this.path = FilenameUtils.separatorsToUnix(path.getAbsolutePath());
this.config = toCompassConfigRubyScript(options);
}
public static String getRelativePathFromWiki(final String targetPath/* , String basePath, String pathSeparator */) {
final File tmp = new File(Constants.WIKI_FOLDER);
final String basePath = tmp.getAbsolutePath();
final String pathSeparator = "/";
// Normalize the paths
String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);
// Undo the changes to the separators made by normalization
if (pathSeparator.equals("/")) {
normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
} else if (pathSeparator.equals("\\")) {
normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
} else {
throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
}
final String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
final String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));
// First get all the common elements. Store them as a string,
// and also count how many of them there are.
final StringBuffer common = new StringBuffer();
int commonIndex = 0;
while (commonIndex < target.length && commonIndex < base.length
&& target[commonIndex].equals(base[commonIndex])) {
common.append(target[commonIndex] + pathSeparator);
commonIndex++;
}
if (commonIndex == 0) {
// No single common path element. This most
// likely indicates differing drive letters, like C: and D:.
// These paths cannot be relativized.
throw new PathResolutionException(
"No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + "'");
}
// The number of directories we have to backtrack depends on whether the base is a file or a dir
// For example, the relative path from
//
// /foo/bar/baz/gg/ff to /foo/bar/baz
//
// ".." if ff is a file
// "../.." if ff is a directory
//
// The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
// the resource referred to by this path may not actually exist, but it's the best I can do
boolean baseIsFile = true;
final File baseResource = new File(normalizedBasePath);
if (baseResource.exists()) {
baseIsFile = baseResource.isFile();
} else if (basePath.endsWith(pathSeparator)) {
baseIsFile = false;
}
final StringBuffer relative = new StringBuffer();
if (base.length != commonIndex) {
final int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;
for (int i = 0; i < numDirsUp; i++) {
relative.append(".." + pathSeparator);
}
}
relative.append(normalizedTargetPath.substring(common.length()));
return relative.toString();
}
public static String applyBaseDirIfRelativeAndNormalize(File baseDir, File actualFileToUse) {
return FilenameUtils.separatorsToUnix(applyBaseDirIfRelative(baseDir, actualFileToUse).getPath());
}
/**
* Gets the full path from a full filename, handles URLs specifically.
* Replaces backslashes with forward slashes.
* <p>
* This method will handle a file in either Unix or Windows format.
* The method is entirely text based, and returns the text before and including the last forward or backslash.
* </p>
*
* @param url - input URL or File path
*
* @return the file path
*
* @see FilenameUtils#getFullPath(String)
* @see #getPrefixLength(String)
*/
public static String getFilePath(String url) {
if (url == null) {
return null;
}
String[] parts = splitFilePath(url);
return FilenameUtils.separatorsToUnix(parts[0] + FilenameUtils.getFullPath(parts[1]));
}
/**
* @param pattern
* the pattern to set
*/
public void setPattern(final String pattern) {
this.pattern = FilenameUtils.separatorsToUnix(pattern);
}