java.io.File.toURL()方法的使用及代码示例

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

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

File.toURL介绍

[英]Returns a Uniform Resource Locator for this file. The URL is system dependent and may not be transferable between different operating / file systems.
[中]返回此文件的统一资源定位器。URL依赖于系统,不能在不同的操作系统/文件系统之间传输。

代码示例

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

ClassLoader currentThreadClassLoader
 = Thread.currentThread().getContextClassLoader();

// Add the conf dir to the classpath
// Chain the current thread classloader
URLClassLoader urlClassLoader
 = new URLClassLoader(new URL[]{new File("mtFile").toURL()},
           currentThreadClassLoader);

// Replace the thread classloader - assumes
// you have permissions to do so
Thread.currentThread().setContextClassLoader(urlClassLoader);

代码示例来源:origin: apache/avro

private URL findFile(String importFile) throws IOException {
 File file = new File(this.inputDir, importFile);
 URL result = null;
 if (file.exists())
  result = file.toURL();
 else if (this.resourceLoader != null)
  result = this.resourceLoader.getResource(importFile);
 if (result == null)
  throw new FileNotFoundException(importFile);
 return result;
}

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

public static void addPath(String s) throws Exception {
  File f = new File(s);
  URL u = f.toURL();
  URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  Class urlClass = URLClassLoader.class;
  Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});
  method.setAccessible(true);
  method.invoke(urlClassLoader, new Object[]{u});
}

代码示例来源:origin: apache/hive

/**
 * Create a URL from a string representing a path to a local file.
 * The path string can be just a path, or can start with file:/, file:///
 * @param onestr  path string
 * @return
 */
private static URL urlFromPathString(String onestr) {
 URL oneurl = null;
 try {
  if (onestr.startsWith("file:/")) {
   oneurl = new URL(onestr);
  } else {
   oneurl = new File(onestr).toURL();
  }
 } catch (Exception err) {
  LOG.error("Bad URL " + onestr + ", ignoring path");
 }
 return oneurl;
}

代码示例来源:origin: apache/hive

try {
 if (StringUtils.indexOf(path, "file:/") == 0) {
  url = new URL(path);
 } else if (StringUtils.indexOf(path, "hdfs:/") == 0
   || StringUtils.indexOf(path, "viewfs:/") == 0) {
   currentTS = -1L;
  if (!new File(localFile.toString()).exists() || currentTS < timeStamp) {
   LOG.info("Copying " + remoteFile + " to " + localFile);
   FileSystem remoteFS = remoteFile.getFileSystem(conf);
  url = new File(path).toURL();

代码示例来源:origin: apache/hive

public boolean addlocaldriverjar(String line) {
 // If jar file is in the hdfs, it should be downloaded first.
 String jarPath = arg1(line, "jar path");
 File p = new File(jarPath);
 if (!p.exists()) {
  beeLine.error("The jar file in the path " + jarPath + " can't be found!");
  return false;
 }
 URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
 try {
  beeLine.debug(jarPath + " is added to the local beeline.");
  URLClassLoader newClassLoader = new URLClassLoader(new URL[]{p.toURL()}, classLoader);
  Thread.currentThread().setContextClassLoader(newClassLoader);
  beeLine.setDrivers(Arrays.asList(beeLine.scanDrivers(false)));
 } catch (Exception e) {
  beeLine.error("Fail to add local jar due to the exception:" + e);
  beeLine.error(e);
 }
 return true;
}

代码示例来源:origin: apache/geode

if (!xmlFile.exists() || !xmlFile.isFile()) {
} else {
 try {
  url = xmlFile.toURL();
 } catch (MalformedURLException ex) {
  throw new CacheXmlException(
 File defaultFile = DistributionConfig.DEFAULT_CACHE_XML_FILE;
 if (!xmlFile.equals(defaultFile)) {
  if (!xmlFile.exists()) {
   throw new CacheXmlException(
     String.format("Declarative Cache XML file/resource %s does not exist.",

代码示例来源:origin: org.codehaus.woodstox/woodstox-core-asl

protected XMLStreamReader2 createSR(File f, boolean forER, boolean autoCloseInput)
  throws XMLStreamException
{
  ReaderConfig cfg = createPrivateConfig();
  try {
    /* 18-Nov-2008, TSa: If P_BASE_URL is set, and File reference is
     *   relative, let's resolve against base...
     */
    if (!f.isAbsolute()) {
      URL base = cfg.getBaseURL();
      if (base != null) {
        URL src = new URL(base, f.getPath());
        return createSR(cfg, SystemId.construct(src), URLUtil.inputStreamFromURL(src),
            forER, autoCloseInput);
      }
    }
    final SystemId systemId = SystemId.construct(f.toURL());
    return createSR(cfg, systemId, new FileInputStream(f), forER, autoCloseInput);
  } catch (IOException ie) {
    throw new WstxIOException(ie);
  }
}

代码示例来源:origin: mulesoft/mule

private URLClassLoader createExtensionClassLoader(File targetFolder) {
  URLClassLoader urlClassLoader;
  try {
   urlClassLoader = new URLClassLoader(new URL[] {targetFolder.toURL()});
  } catch (MalformedURLException e) {
   throw new RuntimeException(e);
  }
  return urlClassLoader;
 }
}

代码示例来源:origin: ronmamo/reflections

/**
 * Returns the URL of the {@code WEB-INF/classes} folder.
 * <p>
 * This finds the URLs using the {@link ServletContext}.
 * 
 * @return the collection of URLs, not null
 */
public static URL forWebInfClasses(final ServletContext servletContext) {
  try {
    final String path = servletContext.getRealPath("/WEB-INF/classes");
    if (path != null) {
      final File file = new File(path);
      if (file.exists())
        return file.toURL();
    } else {
      return servletContext.getResource("/WEB-INF/classes");
    }
  } catch (MalformedURLException e) { /*fuck off*/ }
  return null;
}

代码示例来源:origin: apache/hive

/**
 * Create a URL from a string representing a path to a local file.
 * The path string can be just a path, or can start with file:/, file:///
 * @param onestr  path string
 * @return
 */
private static URL urlFromPathString(String onestr) {
 URL oneurl = null;
 try {
  if (StringUtils.indexOf(onestr, "file:/") == 0) {
   oneurl = new URL(onestr);
  } else {
   oneurl = new File(onestr).toURL();
  }
 } catch (Exception err) {
  LOG.error("Bad URL {}, ignoring path", onestr);
 }
 return oneurl;
}

代码示例来源:origin: Impetus/Kundera

subList.add(new URL(cpEntry));
File file = new File(url.getPath() + classRelativePath + ".class");
if (file.exists())
    list.add(file.toURL());

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

File file  = new File("c:\\myjar.jar");

URL url = file.toURL();  
URL[] urls = new URL[]{url};

ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");

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

this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())

代码示例来源:origin: vipshop/Saturn

File saturnAppLibDir = new File(
    project.getBuild().getDirectory() + System.getProperty("file.separator") + "saturn-run");
if (!saturnAppLibDir.exists()) {
  saturnAppLibDir.mkdirs();
  List<String> runtimeArtifacts = project.getRuntimeClasspathElements();
  for (String path : runtimeArtifacts) {
    File tmp = new File(path);
    copy(tmp, saturnAppLibDir);
  throw new MojoExecutionException("unzip saturn-executor.zip failed", e);
File saturnExecutorDir = new File(saturnHomeCaches, "saturn-executor-" + saturnVersion);
  executorClassLoader = new URLClassLoader(
      new URL[] { new File(saturnExecutorDir, "saturn-executor.jar").toURL() },
      ClassLoader.getSystemClassLoader());
} catch (MalformedURLException e) {

代码示例来源:origin: org.eclipse/org.eclipse.pde.core

public SchemaDescriptor(File file) {
  try {
    if (file.exists()) {
      fSchemaURL = file.toURL();
      fLastModified = file.lastModified();
    }
  } catch (MalformedURLException e) {
  }
}

代码示例来源:origin: org.eclipse/osgi

@SuppressWarnings("deprecation")
public URL getLocalURL() {
  try {
    return new URL("jar:" + bundleFile.basefile.toURL() + "!/" + zipEntry.getName()); //$NON-NLS-1$//$NON-NLS-2$
  } catch (MalformedURLException e) {
    //This can not happen. 
    return null;
  }
}

代码示例来源:origin: net.sf.ehcache/ehcache

public Class<?> run() throws Exception {
    try {
      return ClassLoader.getSystemClassLoader().loadClass(VIRTUAL_MACHINE_CLASSNAME);
    } catch (ClassNotFoundException cnfe) {
      for (File jar : getPossibleToolsJars()) {
        try {
          Class<?> vmClass = new URLClassLoader(new URL[] {jar.toURL()}).loadClass(VIRTUAL_MACHINE_CLASSNAME);
          LOGGER.info("Located valid 'tools.jar' at '{}'", jar);
          return vmClass;
        } catch (Throwable t) {
          LOGGER.info("Exception while loading tools.jar from '{}': {}", jar, t);
        }
      }
      throw new ClassNotFoundException(VIRTUAL_MACHINE_CLASSNAME);
    }
  }
});

代码示例来源:origin: org.reflections/reflections

/**
 * Returns the URL of the {@code WEB-INF/classes} folder.
 * <p>
 * This finds the URLs using the {@link ServletContext}.
 * 
 * @return the collection of URLs, not null
 */
public static URL forWebInfClasses(final ServletContext servletContext) {
  try {
    final String path = servletContext.getRealPath("/WEB-INF/classes");
    if (path != null) {
      final File file = new File(path);
      if (file.exists())
        return file.toURL();
    } else {
      return servletContext.getResource("/WEB-INF/classes");
    }
  } catch (MalformedURLException e) { /*fuck off*/ }
  return null;
}

代码示例来源:origin: apache/drill

/**
 * Create a URL from a string representing a path to a local file.
 * The path string can be just a path, or can start with file:/, file:///
 * @param onestr  path string
 * @return
 */
private static URL urlFromPathString(String onestr) {
 URL oneurl = null;
 try {
  if (StringUtils.indexOf(onestr, "file:/") == 0) {
   oneurl = new URL(onestr);
  } else {
   oneurl = new File(onestr).toURL();
  }
 } catch (Exception err) {
  LOG.error("Bad URL " + onestr + ", ignoring path");
 }
 return oneurl;
}

相关文章