Path Util : Path « File Input Output « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » File Input Output » Path 




Path Util
       
/*
 * Copyright 2005-2010 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package sdloader.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Stack;

/**
 * PathUtils
 
 @author c9katayama
 
 */
public class PathUtil {
  /**
   * ????//???./???../?????????.
   */
  public static String narrow(String path) {
    path = replaceFileSeparator(path);

    String[] paths = path.split("/");
    Stack<String> narrowPathList = new Stack<String>();
    for (int i = 0; i < paths.length; i++) {
      if (paths[i].length() == || paths[i].equals(".")) {
        continue;
      else if (paths[i].equals("..")) {
        if (narrowPathList.size() != 0) {
          narrowPathList.pop();
        }
      else {
        narrowPathList.add(paths[i]);
      }
    }
    boolean first = true;
    String newPath = null;
    for (String p : narrowPathList) {
      if (first) {
        newPath = path.startsWith("/""/" "";
        first = false;
      else {
        newPath += "/";
      }
      newPath += p;
    }
    if (path.endsWith("/")) {
      newPath += "/";
    }
    return newPath;
  }

  /**
   * ????????????????????
   
   @param basePath
   @param path
   @return
   */
  public static String computeRelativePath(String basePath, String path) {
    basePath = basePath.substring(0, basePath.lastIndexOf("/"));
    return jointPathWithSlash(basePath, path);
  }

  /**
   * 2?????"/"???????
   */
  public static String jointPathWithSlash(String path1, String path2) {
    path1 = removeEndSlashIfNeed(path1);
    path2 = removeStartSlashIfNeed(path2);
    return path1 + "/" + path2;
  }

  public static String appendStartSlashIfNeed(final String path) {
    if (path != null && !startsWithSlash(path)) {
      return "/" + path;
    }
    return path;
  }

  public static String appendEndSlashIfNeed(final String path) {
    if (path != null && !endsWithSlash(path)) {
      return path + "/";
    }
    return path;
  }

  public static String removeStartSlashIfNeed(final String path) {
    if (path != null && startsWithSlash(path)) {
      return path.substring(1, path.length());
    }
    return path;
  }

  public static String removeEndSlashIfNeed(final String path) {
    if (path != null && path.endsWith("/")) {
      return path.substring(0, path.length() 1);
    }
    return path;
  }

  public static boolean startsWithSlash(final String path) {
    if (isEmpty(path)) {
      return false;
    }
    return path.indexOf("/"== 0;
  }

  public static boolean endsWithSlash(final String path) {
    if (isEmpty(path)) {
      return false;
    }
    return path.lastIndexOf("/"== path.length() 1;
  }

  private static boolean isEmpty(String value) {
    return (value == null || value.trim().length() == 0);
  }

  /**
   * ????\\?/????????
   
   @param filepath
   @return
   */
  public static final String replaceFileSeparator(String path) {
    return path.replace('\\''/');
  }

  public static final String getExtension(String path) {
    if (path == null) {
      return path;
    }
    int dot = path.lastIndexOf(".");
    if (dot == -1) {
      return null;
    }
    return path.substring(dot + 1, path.length());
  }

  /**
   * ????????
   
   @param path
   @return
   */
  public static final boolean isAbsolutePath(String path) {
    String testPath = replaceFileSeparator(path);
    if (testPath.startsWith("/"|| testPath.indexOf(":"!= -1) {
      return true;
    else {
      return false;
    }
  }

  public static URL file2URL(String filePath) {
    return file2URL(new File(filePath));
  }

  public static URL file2URL(File file) {
    try {
      return file.toURI().toURL();
    catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }

  public static File url2File(String urlPath) {
    try {
      return new File(new URI(urlPath));
    catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }

  public static File url2File(URL url) {
    try {
      return new File(new URI(url.toExternalForm()));
    catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }
}

   
    
    
    
    
    
    
  














Related examples in the same category
1.Returns the path of the given resource.
2.Remove path and file information from a filename returning only its extension component
3.Absolutize a relative resource path on the given absolute base path.
4.Remove File Name SuffixRemove File Name Suffix
5.A utility class for manipulating paths
6.Strip File Extension
7.Get relative path
8.Fixes the file sperator char for the target platform using the following replacement.
9.Concatenates an array of string using a seperator.
10.Rename To Temporary Name
11.Match a path which may contain a wildcard
12.Merges the two paths to create a valid version of the second path
13.General filename and filepath manipulation utilities
14.Extract File Extension
15.Get File Name SuffixGet File Name Suffix
16.Extract the page path from the given request path
17.File name Utils
18.Convert a list of path elements to a platform-specific path.
19.Change File Name To Class NameChange File Name To Class Name
20.strip Extension name
21.Create File Name with specified white space character
22.Build a relative path to the given base path
23.Checks, whether the child directory is a subdirectory of the base directory.
24.Return a context-relative path, beginning with a "/", that represents the canonical version of the specified path after ".." and "." elements are resolved out.
25.Return the path within a base directory
26.Decode a path.
27.Convert a path to a cananonical form
28.Extract file name (without path and suffix) from file name with path and suffix
29.Extract file name (without path but with suffix) from file name with path and suffix
30.Build a path, but do not create it
31.Build a directory path - creating directories if neccesary
32.Collection of file path related stuff
33.Get the first/last token from a path
34.Calculates the relative path between a specified root directory and a target path.
35.Get relative Path
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.