java.net.URL.getPath()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.2k)|赞(0)|评价(0)|浏览(390)

本文整理了Java中java.net.URL.getPath()方法的一些代码示例,展示了URL.getPath()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。URL.getPath()方法的具体详情如下:
包路径:java.net.URL
类名称:URL
方法名:getPath

URL.getPath介绍

[英]Returns the path part of this URL.
[中]返回此URL的路径部分。

代码示例

代码示例来源:origin: spring-projects/spring-framework

/**
 * Determine whether the given URL points to a jar file itself,
 * that is, has protocol "file" and ends with the ".jar" extension.
 * @param url the URL to check
 * @return whether the URL has been identified as a JAR file URL
 * @since 4.1
 */
public static boolean isJarFileURL(URL url) {
  return (URL_PROTOCOL_FILE.equals(url.getProtocol()) &&
      url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION));
}

代码示例来源:origin: google/guava

@VisibleForTesting
 static File toFile(URL url) {
  checkArgument(url.getProtocol().equals("file"));
  try {
   return new File(url.toURI()); // Accepts escaped characters like %20.
  } catch (URISyntaxException e) { // URL.toURI() doesn't escape chars.
   return new File(url.getPath()); // Accepts non-escaped chars like space.
  }
 }
}

代码示例来源:origin: Netflix/eureka

public DefaultEndpoint(String serviceUrl) {
  this.serviceUrl = serviceUrl;
  try {
    URL url = new URL(serviceUrl);
    this.networkAddress = url.getHost();
    this.port = url.getPort();
    this.isSecure = "https".equals(url.getProtocol());
    this.relativeUri = url.getPath();
  } catch (Exception e) {
    throw new IllegalArgumentException("Malformed serviceUrl: " + serviceUrl);
  }
}

代码示例来源:origin: robolectric/robolectric

@Override
public boolean isValid(URL url) {
 return new File(url.getPath()).exists();
}

代码示例来源:origin: btraceio/btrace

private File getContainingJar(String clz) {
  File jarFile;
  URL url = getClass().getClassLoader().getResource(clz);
  if ("jar".equals(url.getProtocol())) { //NOI18N
    String path = url.getPath();
    int index = path.indexOf("!/"); //NOI18N
    if (index >= 0) {
      try {
        String jarPath = path.substring(0, index);
        if (jarPath.contains("file://") && !jarPath.contains("file:////")) {  //NOI18N
          /* Replace because JDK application classloader wrongly recognizes UNC paths. */
          jarPath = jarPath.replaceFirst("file://", "file:////");  //NOI18N
        }
        url = new URL(jarPath);
      } catch (MalformedURLException mue) {
        throw new RuntimeException(mue);
      }
    }
  }
  try {
    jarFile = new File(url.toURI());
  } catch (URISyntaxException ex) {
    throw new RuntimeException(ex);
  }
  assert jarFile.exists();
  return jarFile;
}

代码示例来源:origin: code4craft/webmagic

private void initPhantomjsCrawlPath() {
  PhantomJSDownloader.crawlJsPath = new File(this.getClass().getResource("/").getPath()).getPath() + System.getProperty("file.separator") + "crawl.js ";
}

代码示例来源:origin: Tencent/tinker

private static void setRunningLocation(CliMain m) {
  mRunningLocation = m.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
  try {
    mRunningLocation = URLDecoder.decode(mRunningLocation, "utf-8");
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  }
  if (mRunningLocation.endsWith(".jar")) {
    mRunningLocation = mRunningLocation.substring(0, mRunningLocation.lastIndexOf(File.separator) + 1);
  }
  File f = new File(mRunningLocation);
  mRunningLocation = f.getAbsolutePath();
}

代码示例来源:origin: stackoverflow.com

public URL parseUrl(String s) throws Exception {
   URL u = new URL(s);
   return new URI(
      u.getProtocol(), 
      u.getAuthority(), 
      u.getPath(),
      u.getQuery(), 
      u.getRef()).
      toURL();
}

代码示例来源:origin: stackoverflow.com

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilTest {

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test");

    System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
    System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
    System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
  }

}

代码示例来源:origin: wildfly/wildfly

public PreSignedUrlParser(String preSignedUrl) {
  try {
    URL url = new URL(preSignedUrl);
    this.bucket = parseBucketFromHost(url.getHost());
    String path = url.getPath();
    String[] pathParts = path.split("/");
    
    if (pathParts.length < 2) {
      throw new IllegalArgumentException("pre-signed url " + preSignedUrl + " must point to a file within a bucket");
    }
    if (pathParts.length > 3) {
      throw new IllegalArgumentException("pre-signed url " + preSignedUrl + " may only have only subdirectory under a bucket");
    }
    if (pathParts.length > 2) {
      this.prefix = pathParts[1];
    }
  } catch (MalformedURLException ex) {
    throw new IllegalArgumentException("pre-signed url " + preSignedUrl + " is not a valid url");
  }
}

代码示例来源:origin: voldemort/voldemort

public static String findContainingJar(String fileName, ClassLoader loader) {
  try {
    for(Enumeration itr = loader.getResources(fileName); itr.hasMoreElements();) {
      URL url = (URL) itr.nextElement();
      logger.info("findContainingJar finds url:" + url);
      if("jar".equals(url.getProtocol())) {
        String toReturn = url.getPath();
        if(toReturn.startsWith("file:")) {
          toReturn = toReturn.substring("file:".length());
        }
        toReturn = URLDecoder.decode(toReturn, "UTF-8");
        return toReturn.replaceAll("!.*$", "");
      }
    }
  } catch(IOException e) {
    throw new RuntimeException(e);
  }
  return null;
}

代码示例来源:origin: stackoverflow.com

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");

代码示例来源:origin: prestodb/presto

/**
 * Helper methods used for constructing an optimal stream for
 * parsers to use, when input is to be read from an URL.
 * This helps when reading file content via URL.
 */
protected InputStream _optimizedStreamFromURL(URL url) throws IOException {
  if ("file".equals(url.getProtocol())) {
    /* Can not do this if the path refers
     * to a network drive on windows. This fixes the problem;
     * might not be needed on all platforms (NFS?), but should not
     * matter a lot: performance penalty of extra wrapping is more
     * relevant when accessing local file system.
     */
    String host = url.getHost();
    if (host == null || host.length() == 0) {
      // [core#48]: Let's try to avoid probs with URL encoded stuff
      String path = url.getPath();
      if (path.indexOf('%') < 0) {
        return new FileInputStream(url.getPath());
      }
      // otherwise, let's fall through and let URL decoder do its magic
    }
  }
  return url.openStream();
}

代码示例来源:origin: alibaba/canal

/**
 * 获取conf文件夹所在路径
 *
 * @return 路径地址
 */
private String getConfPath() {
  String classpath = this.getClass().getResource("/").getPath();
  String confPath = classpath + "../conf/";
  if (new File(confPath).exists()) {
    return confPath;
  } else {
    return classpath;
  }
}

代码示例来源:origin: konsoletyper/teavm

private Date getOriginalModificationDate(String className) {
  if (classLoader == null) {
    return null;
  }
  URL url = classLoader.getResource(className.replace('.', '/') + ".class");
  if (url == null) {
    return null;
  }
  if (url.getProtocol().equals("file")) {
    try {
      File file = new File(url.toURI());
      return file.exists() ? new Date(file.lastModified()) : null;
    } catch (URISyntaxException e) {
      // If URI is invalid, we just report that class should be reparsed
      return null;
    }
  } else if (url.getProtocol().equals("jar") && url.getPath().startsWith("file:")) {
    int exclIndex = url.getPath().indexOf('!');
    String jarFileName = exclIndex >= 0 ? url.getPath().substring(0, exclIndex) : url.getPath();
    File file = new File(jarFileName.substring("file:".length()));
    return file.exists() ? new Date(file.lastModified()) : null;
  } else {
    return null;
  }
}

代码示例来源:origin: google/j2objc

@VisibleForTesting
 static File toFile(URL url) {
  checkArgument(url.getProtocol().equals("file"));
  try {
   return new File(url.toURI()); // Accepts escaped characters like %20.
  } catch (URISyntaxException e) { // URL.toURI() doesn't escape chars.
   return new File(url.getPath()); // Accepts non-escaped chars like space.
  }
 }
}

代码示例来源:origin: stackoverflow.com

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

代码示例来源:origin: gocd/gocd

private static void copyPluginAssets() throws IOException {
  File classPathRoot = new File(DevelopmentServer.class.getProtectionDomain().getCodeSource().getLocation().getPath());
  FileUtils.copyFile(new File("webapp/WEB-INF/rails/webpack/rails-shared/plugin-endpoint.js"), new File(classPathRoot, "plugin-endpoint.js"));
}

代码示例来源:origin: ZHENFENG13/My-Blog

/**
   * 获取保存文件的位置,jar所在目录的路径
   *
   * @return
   */
  public static String getUploadFilePath() {
    String path = TaleUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    path = path.substring(1, path.length());
    try {
      path = java.net.URLDecoder.decode(path, "utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    int lastIndex = path.lastIndexOf("/") + 1;
    path = path.substring(0, lastIndex);
    File file = new File("");
    return file.getAbsolutePath() + "/";
  }
}

代码示例来源:origin: redisson/redisson

/**
   * {@inheritDoc}
   */
  public URL findSealBase(ClassLoader classLoader, String typeName) {
    URL url = classLoader.getResource(typeName.replace('.', '/') + CLASS_FILE_EXTENSION);
    if (url != null) {
      try {
        if (url.getProtocol().equals(JAR_FILE)) {
          return new URL(url.getPath().substring(0, url.getPath().indexOf('!')));
        } else if (url.getProtocol().equals(FILE_SYSTEM)) {
          return url;
        } else if (url.getProtocol().equals(RUNTIME_IMAGE)) {
          String path = url.getPath();
          int modulePathIndex = path.indexOf('/', EXCLUDE_INITIAL_SLASH);
          return modulePathIndex == -1
              ? url
              : new URL(RUNTIME_IMAGE + ":" + path.substring(0, modulePathIndex));
        }
      } catch (MalformedURLException exception) {
        throw new IllegalStateException("Unexpected URL: " + url, exception);
      }
    }
    return fallback.findSealBase(classLoader, typeName);
  }
}

相关文章