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

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

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

URL.toURI介绍

[英]Returns the URI equivalent to this URL.
[中]返回与此URL等效的URI。

代码示例

代码示例来源: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: stackoverflow.com

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

代码示例来源:origin: twosigma/beakerx

protected static boolean isValidURL(String urlString) {
 try {
  URL url = new URL(urlString);
  url.toURI();
  return true;
 } catch (Exception exception) {
  return false;
 }
}

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

public static void checkJarFile(URL jar) throws IOException {
  File jarFile;
  try {
    jarFile = new File(jar.toURI());
  } catch (URISyntaxException e) {
    throw new IOException("JAR file path is invalid '" + jar + "'");
  }
  if (!jarFile.exists()) {
    throw new IOException("JAR file does not exist '" + jarFile.getAbsolutePath() + "'");
  }
  if (!jarFile.canRead()) {
    throw new IOException("JAR file can't be read '" + jarFile.getAbsolutePath() + "'");
  }
  // TODO: Check if proper JAR file
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testUTF8FileWindowsBreaks() throws URISyntaxException, IOException {
  final File testFileIso = new File(this.getClass().getResource("/test-file-utf8-win-linebr.bin").toURI());
  reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, testParamBlockSize, UTF_8);
  assertFileWithShrinkingTestLines(reversedLinesFileReader);
}

代码示例来源:origin: ReactiveX/RxJava

@Test
public void verify() throws Exception {
  URL u = NoAnonymousInnerClassesTest.class.getResource("/");
  File f = new File(u.toURI());
  String prefix = f.getAbsolutePath();
  int count = 0;
  while (!queue.isEmpty()) {
        for (String s : parts) {
          if (Character.isDigit(s.charAt(0))) {
            String n = f.getAbsolutePath().substring(prefix.length()).replace('\\', '.').replace('/', '.');
            if (n.startsWith(".")) {
              n = n.substring(1);

代码示例来源:origin: HotswapProjects/HotswapAgent

/**
   * Create all required directories in path for a file
   */
  public static void assertDirExists(URL targetFile) {
    File parent = null;
    try {
      parent = new File(targetFile.toURI()).getParentFile();
    } catch (URISyntaxException e) {
      throw new IllegalStateException(e);
    }

    if(!parent.exists() && !parent.mkdirs()){
      throw new IllegalStateException("Couldn't create dir: " + parent);
    }
  }
}

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

private String filePath(String filename) {
  URL fileUrl = getClass().getClassLoader().getResource(filename);
  try {
    return new File(fileUrl.toURI()).getAbsolutePath();
  } catch (URISyntaxException e) {
    return fileUrl.getPath();
  }
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testDataIntegrityWithBufferedReader() throws URISyntaxException, IOException {
  final File testFileIso = new File(this.getClass().getResource("/" + fileName).toURI());
  reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, buffSize, encoding);
  final Stack<String> lineStack = new Stack<>();
  bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(testFileIso), encoding));
  String line = null;
  // read all lines in normal order
  while ((line = bufferedReader.readLine()) != null) {
    lineStack.push(line);
  }
  // read in reverse order and compare with lines from stack
  while ((line = reversedLinesFileReader.readLine()) != null) {
    final String lineFromBufferedReader = lineStack.pop();
    assertEquals(lineFromBufferedReader, line);
  }
}

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

@Test
public void testFileSystemResourceWithFilePath() throws Exception {
  Path filePath = Paths.get(getClass().getResource("Resource.class").toURI());
  Resource resource = new FileSystemResource(filePath);
  doTestResource(resource);
  assertEquals(new FileSystemResource(filePath), resource);
}

代码示例来源:origin: jenkinsci/jenkins

private static String getUnmigrationCommandLine(File jenkinsHome) {
  StringBuilder cp = new StringBuilder();
  for (Class<?> c : new Class<?>[] {RunIdMigrator.class, /* TODO how to calculate transitive dependencies automatically? */Charsets.class, WriterOutputStream.class, BuildException.class, FastDateFormat.class}) {
    URL location = c.getProtectionDomain().getCodeSource().getLocation();
    String locationS = location.toString();
    if (location.getProtocol().equals("file")) {
      try {
        locationS = new File(location.toURI()).getAbsolutePath();
      } catch (URISyntaxException x) {
        // never mind
      }
    }
    if (cp.length() > 0) {
      cp.append(File.pathSeparator);
    }
    cp.append(locationS);
  }
  return String.format("java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testURL() throws Exception {
 URL url = new URL("http://www.cheese.com/asiago");
 Properties props = new Properties();
 props.put(DefaultConfigurationResolver.DEFAULT_CONFIG_PROPERTY_NAME, url);
 URI resolved = DefaultConfigurationResolver.resolveConfigURI(props);
 assertEquals(url.toURI(), resolved);
}

代码示例来源:origin: micronaut-projects/micronaut-core

private Optional<? extends FileCustomizableResponseType> matchFile(String path) {
  Optional<URL> optionalUrl = staticResourceResolver.resolve(path);
  if (optionalUrl.isPresent()) {
    try {
      URL url = optionalUrl.get();
      if (url.getProtocol().equals("file")) {
        File file = Paths.get(url.toURI()).toFile();
        if (file.exists() && !file.isDirectory() && file.canRead()) {
          return Optional.of(new NettySystemFileCustomizableResponseType(file));
        }
      }
      return Optional.of(new NettyStreamedFileCustomizableResponseType(url));
    } catch (URISyntaxException e) {
      //no-op
    }
  }
  return Optional.empty();
}

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

@Test
public void testFileSystemResourceWithImport() throws URISyntaxException {
  String file = getClass().getResource(RESOURCE_CONTEXT.getPath()).toURI().getPath();
  DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
  new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(new FileSystemResource(file));
  // comes from "resourceImport.xml"
  xbf.getBean("resource1", ResourceTestBean.class);
  // comes from "resource.xml"
  xbf.getBean("resource2", ResourceTestBean.class);
}

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

@Override
public Path getFilePath() {
  if (url.getProtocol().equals("file")) {
    try {
      return Paths.get(url.toURI());
    } catch (URISyntaxException e) {
      return null;
    }
  }
  return null;
}

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

public static File getFile(String classPathLocation) throws IOException, URISyntaxException {
    URL resource = PropertyFileConfigurationSource.class.getClassLoader().getResource(classPathLocation);
    if (resource == null) {
      resource = new URL("file://" + classPathLocation);
    }
    if (!"file".equals(resource.getProtocol())) {
      throw new IOException("Saving to property files inside a war, ear or jar is not possible.");
    }
    return new File(resource.toURI());
  }
}

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

@Override
  public String toString() {
    final URL location = klass.getProtectionDomain().getCodeSource().getLocation();
    try {
      final String jar = new File(location.toURI()).getName();
      if (jar.endsWith(".jar")) {
        return jar;
      }
      return "project.jar";
    } catch (Exception ignored) {
      return "project.jar";
    }
  }
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testUTF16LEFile() throws URISyntaxException, IOException {
  final File testFileUTF16LE = new File(this.getClass().getResource("/test-file-utf16le.bin").toURI());
  reversedLinesFileReader = new ReversedLinesFileReader(testFileUTF16LE, testParamBlockSize, "UTF-16LE");
  assertFileWithShrinkingTestLines(reversedLinesFileReader);
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void binary_file_with_unmappable_character() throws Exception {
 File woff = new File(this.getClass().getResource("glyphicons-halflings-regular.woff").toURI());
 Metadata metadata = new FileMetadata().readMetadata(new FileInputStream(woff), StandardCharsets.UTF_8, woff.getAbsolutePath());
 assertThat(metadata.lines()).isEqualTo(135);
 assertThat(metadata.nonBlankLines()).isEqualTo(133);
 assertThat(metadata.hash()).isNotEmpty();
 assertThat(logTester.logs(LoggerLevel.WARN).get(0)).contains("Invalid character encountered in file");
 assertThat(logTester.logs(LoggerLevel.WARN).get(0)).contains(
  "glyphicons-halflings-regular.woff at line 1 for encoding UTF-8. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'.");
}

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

/**try to get {@link java.io.File} from url*/
public static @Nullable java.io.File getFile(URL url) {
  java.io.File file;
  String path;
  try {
    path = url.toURI().getSchemeSpecificPart();
    if ((file = new java.io.File(path)).exists()) return file;
  } catch (URISyntaxException e) {
  }
  try {
    path = URLDecoder.decode(url.getPath(), "UTF-8");
    if (path.contains(".jar!")) path = path.substring(0, path.lastIndexOf(".jar!") + ".jar".length());
    if ((file = new java.io.File(path)).exists()) return file;
  } catch (UnsupportedEncodingException e) {
  }
  try {
    path = url.toExternalForm();
    if (path.startsWith("jar:")) path = path.substring("jar:".length());
    if (path.startsWith("wsjar:")) path = path.substring("wsjar:".length());
    if (path.startsWith("file:")) path = path.substring("file:".length());
    if (path.contains(".jar!")) path = path.substring(0, path.indexOf(".jar!") + ".jar".length());
    if (path.contains(".war!")) path = path.substring(0, path.indexOf(".war!") + ".war".length());
    if ((file = new java.io.File(path)).exists()) return file;
    path = path.replace("%20", " ");
    if ((file = new java.io.File(path)).exists()) return file;
  } catch (Exception e) {
  }
  return null;
}

相关文章