/** * Creates a resource from a {@code Path}. * <p> * This will return either a file locator or a URL locator. * * @param path path to the file to wrap * @return the resource locator * @throws IllegalArgumentException if the path is neither a file nor a URL */ public static ResourceLocator ofPath(Path path) { ArgChecker.notNull(path, "path"); try { return ofFile(path.toFile()); } catch (UnsupportedOperationException ex) { try { return ofUrl(path.toUri().toURL()); } catch (MalformedURLException ex2) { throw new IllegalArgumentException("Path could not be converted to a File or URL: " + path); } } }
/** * Creates a resource from a string locator. * <p> * This accepts locators starting with 'classpath:', 'url:' or 'file:'. * It also accepts unprefixed locators, treated as files. * * @param locator the string form of the resource locator * @return the resource locator */ @FromString public static ResourceLocator of(String locator) { ArgChecker.notNull(locator, "locator"); try { if (locator.startsWith(CLASSPATH_URL_PREFIX)) { String urlStr = locator.substring(CLASSPATH_URL_PREFIX.length()); return ofClasspath(urlStr); } else if (locator.startsWith(FILE_URL_PREFIX)) { String fileStr = locator.substring(FILE_URL_PREFIX.length()); return ofFile(new File(fileStr)); } else if (locator.startsWith(URL_PREFIX)) { String pathStr = locator.substring(URL_PREFIX.length()); return ofUrl(new URL(pathStr)); } else { return ofFile(new File(locator)); } } catch (Exception ex) { throw new IllegalArgumentException("Invalid resource locator: " + locator, ex); } }
public void test_ofUrl() throws Exception { File file = new File("src/test/resources/com/opengamma/strata/collect/io/TestFile.txt"); URL url = file.toURI().toURL(); ResourceLocator test = ResourceLocator.ofUrl(url); String locator = test.getLocator(); assertTrue(locator.startsWith("url:file:")); assertTrue(locator.endsWith("src/test/resources/com/opengamma/strata/collect/io/TestFile.txt")); assertEquals(test.getByteSource().read()[0], 'H'); assertEquals(test.getCharSource().readLines(), ImmutableList.of("HelloWorld")); assertEquals(test.getCharSource(StandardCharsets.UTF_8).readLines(), ImmutableList.of("HelloWorld")); assertEquals(test.toString(), locator); }