下面列出了怎么用java.nio.file.Path的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
}
else {
throw new StorageFileNotFoundException(
"Could not read file: " + filename);
}
}
catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
/**
* Create a history tree from an existing file
*
* @param treeFile
* Filename/location of the history we want to load
* @param intervalReader
* Factory to read history tree objects from the backend
* @param version
* The version number of the reader/writer
* @return The new history tree
* @throws IOException
* If we can't read the file, if it doesn't exist, is not
* recognized, or if the version of the file does not match the
* expected providerVersion.
*/
private SegmentHistoryTree<E> createHistoryTree(Path treeFile, IHTIntervalReader<@NonNull E> intervalReader, int version) throws IOException {
try {
if (Files.exists(treeFile)) {
SegmentHistoryTree<E> sht = new SegmentHistoryTree<>(NonNullUtils.checkNotNull(treeFile.toFile()), version, intervalReader);
fFinishedBuilding = true;
return sht;
}
} catch (IOException e) {
/**
* Couldn't create the history tree with this file, just fall back
* to a new history tree
*/
}
return new SegmentHistoryTree<>(NonNullUtils.checkNotNull(treeFile.toFile()),
BLOCK_SIZE,
MAX_CHILDREN,
version,
0,
intervalReader);
}
/**
* @throws JobExecutionException
*/
private void createMetaFile() throws JobExecutionException {
java.nio.file.Path metadataFile = ExportPathBuilder.getInstance().getPerJobIdMetadataFile(resourcePath, userProfile, id);
try {
String docLabel = documentExportConf.getDocumentLabel();
ExportMetadata exportMetadata = new ExportMetadata();
exportMetadata.setId(id);
exportMetadata.setDataSetName(docLabel);
exportMetadata.setFileName(docLabel + "." + extension());
exportMetadata.setMimeType(mime());
exportMetadata.setStartDate(Calendar.getInstance(locale).getTime());
ExportMetadata.writeToJsonFile(exportMetadata, metadataFile);
} catch (Exception e) {
deleteJobDirectory();
String msg = String.format("Error creating file \"%s\"!", metadataFile);
throw new JobExecutionException(msg, e);
}
}
Map<Route, WebClient> load(Path configPath) {
final RoutingConfig config;
try {
config = OBJECT_MAPPER.readValue(configPath.toFile(), RoutingConfig.class);
} catch (IOException e) {
throw new UncheckedIOException("Could not read routing config.", e);
}
Map<String, WebClient> clients =
config.getTargets().stream()
.collect(
toImmutableMap(
Target::getName,
t ->
clientBuilderFactory
.create(t.getName(), addSerializationFormat(t.getUrl()))
.build(WebClient.class)));
return config.getRules().stream()
.collect(
toImmutableMap(
r -> Route.builder().path(r.getPathPattern()).build(),
r -> clients.get(r.getTarget())));
}
public void addJarDependency(BOperatorInvocation op, Class<?> clazz) {
CodeSource thisCodeSource = this.getClass().getProtectionDomain()
.getCodeSource();
CodeSource source = clazz.getProtectionDomain().getCodeSource();
if (null == source || thisCodeSource.equals(source)) {
return;
}
Path absolutePath = null;
try {
absolutePath = Paths.get(source.getLocation().toURI()).toAbsolutePath();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
if (operatorToJarDependencies.containsKey(op)) {
operatorToJarDependencies.get(op).add(absolutePath);
} else {
operatorToJarDependencies.put(op, new HashSet<Path>());
operatorToJarDependencies.get(op).add(absolutePath);
}
}
/**
* Walks the trie of paths attempting to merge all of the children of the current path into
* itself.
*
* <p>If a parent folder is present then the merge happens only for children folders that can be
* merged into a parent folder. Otherwise a parent folder is created and matching children
* folders are merged into it.
*
* @param currentPath current path
* @return Optional.of(a successfully merged folder) or absent if merging did not succeed.
*/
private Optional<IjFolder> walk(Path currentPath) {
ImmutableList<Optional<IjFolder>> children =
StreamSupport.stream(tree.getOutgoingNodesFor(currentPath).spliterator(), false)
.map(this::walk)
.collect(ImmutableList.toImmutableList());
ImmutableList<IjFolder> presentChildren =
children.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableList.toImmutableList());
IjFolder currentFolder = mergePathsMap.get(currentPath);
if (presentChildren.isEmpty()) {
return Optional.ofNullable(currentFolder);
}
boolean hasNonPresentChildren = presentChildren.size() != children.size();
return tryMergingParentAndChildren(
currentPath, currentFolder, presentChildren, hasNonPresentChildren);
}
private TestServerRule(
ImmutableMap<String, Path> runfiles,
ImmutableList<Route> routes,
ImmutableList<Class<? extends Filter>> filters,
ImmutableList<Fixture> fixtures,
String email,
Optional<String> gaeUserId) {
this.runfiles = runfiles;
this.routes = routes;
this.filters = filters;
this.fixtures = fixtures;
// We create an GAE-Admin user, and then use AuthenticatedRegistrarAccessor.bypassAdminCheck to
// choose whether the user is an admin or not.
this.appEngineRule =
AppEngineRule.builder()
.withDatastoreAndCloudSql()
.withLocalModules()
.withUrlFetch()
.withTaskQueue()
.withUserService(
UserInfo.createAdmin(email, gaeUserId.orElse(THE_REGISTRAR_GAE_USER_ID)))
.build();
}
@Test
void testUpToDate() throws Exception {
final Path projectDir = TestFiles.helidonSeProject();
final TestMonitor monitor = new TestMonitor(1);
final BuildExecutor executor = new ForkedMavenExecutor(projectDir, monitor, 30);
final ProjectSupplier supplier = new DefaultProjectSupplier();
final Project project = supplier.newProject(executor, false, true,0);
assertThat(project, is(not(nullValue())));
assertThat(project.isBuildUpToDate(), is(true));
assertThat(monitor.buildStart(0), is(false));
assertThat(project, is(not(nullValue())));
MatcherAssert.assertThat(project.root().directoryType(), Matchers.is(DirectoryType.Project));
assertThat(project.root().path(), is(projectDir));
final List<BuildComponent> components = project.components();
assertThat(components, is(not(nullValue())));
assertThat(components.size(), is(2));
assertThat(components.get(0).sourceRoot().path().toString(), endsWith("src/main/java"));
assertThat(components.get(0).outputRoot().path().toString(), endsWith("target/classes"));
assertThat(components.get(1).sourceRoot().path().toString(), endsWith("src/main/resources"));
assertThat(components.get(1).outputRoot().path().toString(), endsWith("target/classes"));
assertThat(components.get(1).outputRoot(), is(not(components.get(0).outputRoot())));
assertThat(project.classpath().size(), is(greaterThan(2)));
assertThat(project.mainClassName(), is("io.helidon.examples.se.Main"));
}
public void testReadSymbolicLinkRelative() throws IOException {
if (!checkSymlinksSupported()) {
return;
}
File dir = getWorkDir();
File folder = new File(dir, "folder");
File link = new File(dir, "link");
folder.mkdir();
Path lp = Files.createSymbolicLink(link.toPath(), Paths.get("folder"));
assertNotNull(lp);
FileObject linkFO = FileUtil.toFileObject(link);
assertNotNull(linkFO);
FileObject dataFO = linkFO.readSymbolicLink();
assertNotSame(linkFO, dataFO);
assertNotNull(dataFO);
assertEquals("folder", dataFO.getNameExt());
}
@Test
public void testSettingsFile() throws Exception {
MavenConfig config = cli.getSession().getPmConfiguration().getMavenConfig();
Path p = cli.newDir("foo", true);
Path settings = p.resolve("settings.xml");
Files.createFile(settings);
Path existingSettings = config.getSettings();
Assert.assertNull(existingSettings);
cli.execute("maven set-settings-file " + settings.toFile().getAbsolutePath());
Assert.assertEquals(settings, config.getSettings());
Assert.assertEquals(settings, Configuration.parse().getMavenConfig().getSettings());
cli.execute("maven get-info");
Assert.assertTrue(cli.getOutput().contains(settings.toFile().getAbsolutePath()));
cli.execute("maven reset-settings-file");
Assert.assertNull(config.getSettings());
Assert.assertNull(Configuration.parse().getMavenConfig().getSettings());
}
/**
* <p>Collect the source files from the {@code dir} directory, create {@link javax0.geci.api.Source Source} objects
* that encapsulate the file and add the new object to the set of sources.</p>
*
* @param onlySet only the files are processed that match some element of this set unless this set is empty. In
* this case the set is not consulted.
* @param ignoreSet
* @param dir
* @throws IOException
*/
private void collectInputDirectory(final Set<Predicate<Path>> onlySet,
final Set<Predicate<Path>> ignoreSet,
final String dir
) throws IOException {
getAllRegularFiles(dir)
.peek(s -> Tracer.push("File", "'" + s + "' was found"))
//
.peek(s -> Tracer.push("Only", "Checking predicates"))
.filter(path -> pathIsMatchingOnlySet(onlySet, path))
.peek(s -> Tracer.pop())
//
.peek(s -> Tracer.push("Ignore", "Checking predicates"))
.filter(path -> pathIsNotIgnored(ignoreSet, path))
.peek(s -> Tracer.pop())
//
.peek(s -> Tracer.pop())
.forEach(path -> sources.add(new Source(this, dir, path)));
}
/**
* Grey out the relevant controls if the checkbox is unchecked, and vice
* versa. Also verify if the current settings are valid, and update the
* window error message if needed.
*/
private void updateContents() {
boolean useCustomDirEnabled = getCurrentCheckBoxState();
checkNotNull(fCustomDirectoryPath).setEnabled(useCustomDirEnabled);
checkNotNull(fBrowseButton).setEnabled(useCustomDirEnabled);
checkNotNull(fClearButton).setEnabled(useCustomDirEnabled);
String errorMessage = null;
if (useCustomDirEnabled) {
String pathPrefix = getCurrentPathPrefix();
Path path = Paths.get(pathPrefix);
if (pathPrefix.equals("") || !Files.isDirectory(path)) { //$NON-NLS-1$
errorMessage = Messages.PreferencePage_ErrorDirectoryDoesNotExists;
}
}
setErrorMessage(errorMessage);
setValid(errorMessage == null);
}
/**
* Creates a file system tree in a temporary directory.
* @param entriesToCreate a list of paths to create. If path ends with '/', it will become a directory; otherwise it
* will become a file
* @return a path to the root of the file system tree.
*/
public static Path createTempFileSystem(String... entriesToCreate) throws IOException {
Path rootDirectory = Files.createTempDirectory("azuredevopstest");
for (String relativePath : entriesToCreate) {
Path resultingPath = rootDirectory.resolve(relativePath);
Path directoryPath = resultingPath.getParent();
Files.createDirectories(directoryPath);
if (relativePath.endsWith("/")) {
Files.createDirectories(resultingPath);
} else {
//noinspection ResultOfMethodCallIgnored
resultingPath.toFile().createNewFile();
}
}
return rootDirectory;
}
private void processSingle(
@NonNull Path input, @NonNull Path output, @NonNull Set<? super QualifiedContent.Scope> scopes)
throws Exception {
waitableExecutor.execute(
() -> {
if (output.toString().endsWith(SdkConstants.DOT_JAR)) {
Files.createDirectories(output.getParent());
} else {
Files.createDirectories(output);
}
FileCache cacheToUse;
if (Files.isRegularFile(input)
&& Objects.equals(
scopes, Collections.singleton(QualifiedContent.Scope.EXTERNAL_LIBRARIES))) {
cacheToUse = userCache;
} else {
cacheToUse = null;
}
processUsingCache(input, output, cacheToUse);
return null;
});
}
private void cleanUp() {
ModelNode op = new ModelNode();
op.get(OP).set(READ_RESOURCE_OPERATION);
op.get(OP_ADDR).set(DEPLOYMENT, TEST_DEPLOYMENT_NAME);
ModelNode result = awaitOperationExecutionAndReturnResult(op);
if (Operations.isSuccessfulOutcome(result)) {
undeployAndRemoveDeployment(TEST_DEPLOYMENT_NAME);
}
String jbossBaseDir = System.getProperty("jboss.home");
Assert.assertNotNull(jbossBaseDir);
Path dataDir = new File(jbossBaseDir).toPath().resolve("standalone").resolve("data");
if (Files.exists(dataDir)) { cleanFile(dataDir.resolve("managed-exploded").toFile()); }
File archivesDir = new File("target", "archives");
if (Files.exists(archivesDir.toPath())) { cleanFile(archivesDir); }
}
/**
* Configure and create a new Installer instance.
*
* @param managedSdkDirectory home directory of google cloud java managed cloud SDKs
* @param version version of the Cloud SDK we want to install
* @param osInfo target operating system for installation
* @param userAgentString user agent string for https requests
* @param usageReporting enable client side usage reporting on gcloud
* @return a new configured Cloud SDK Installer
*/
public static SdkInstaller newInstaller(
Path managedSdkDirectory,
Version version,
OsInfo osInfo,
String userAgentString,
boolean usageReporting) {
DownloaderFactory downloaderFactory = new DownloaderFactory(userAgentString);
ExtractorFactory extractorFactory = new ExtractorFactory();
InstallerFactory installerFactory =
version == Version.LATEST ? new InstallerFactory(osInfo, usageReporting) : null;
FileResourceProviderFactory fileResourceProviderFactory =
new FileResourceProviderFactory(version, osInfo, managedSdkDirectory);
return new SdkInstaller(
fileResourceProviderFactory, downloaderFactory, extractorFactory, installerFactory);
}
private Path findModelFile(String prefix) {
Path modelFile = modelDir.resolve(prefix);
if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) {
if (prefix.endsWith(".ftz") || prefix.endsWith(".bin")) {
return null;
}
modelFile = modelDir.resolve(prefix + ".ftz");
if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) {
modelFile = modelDir.resolve(prefix + ".bin");
if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) {
return null;
}
}
}
return modelFile;
}
@Override
public FileSystem newFileSystem(Path path, Map<String, ?> env) throws IOException {
JimfsPath checkedPath = checkPath(path);
checkNotNull(env);
URI pathUri = checkedPath.toUri();
URI jarUri = URI.create("jar:" + pathUri);
try {
// pass the new jar:jimfs://... URI to be handled by ZipFileSystemProvider
return FileSystems.newFileSystem(jarUri, env);
} catch (Exception e) {
// if any exception occurred, assume the file wasn't a zip file and that we don't support
// viewing it as a file system
throw new UnsupportedOperationException(e);
}
}
private void generatedBin(Map<String, String> contractResult, String contractName) {
if (!StringUtils.containsIgnoreCase(outputFormat, "bin")) {
return;
}
String binJson = contractResult.get(SolidityCompiler.Options.BIN.getName());
try {
String filename = contractName + ".bin";
Path path = createPath(StringUtils.defaultString(outputDirectory.getBin(), sourceDestination));
Files.write(Paths.get(path.toString(), filename), binJson.getBytes());
} catch (IOException e) {
getLog().error("Could not build bin file for contract '" + contractName + "'", e);
}
}
@Test
void readWithContextCustomer() throws Exception {
URL htmlToExcelEampleURL = this.getClass().getResource("/common_build.xls");
Path path = Paths.get(htmlToExcelEampleURL.toURI());
SaxExcelReader.of(CommonPeople.class).rowFilter(row -> row.getRowNum() > 0).readThen(Files.newInputStream(path), (d, context) -> {
System.out.println(d);
});
}
private boolean shouldUpdateSymlinkTree(
Path headerSymlinkTreeRoot,
ImmutableSortedMap<Path, Path> resolvedContents,
boolean shouldCreateHeadersSymlinks,
ImmutableList.Builder<Path> headerSymlinkTreesBuilder)
throws IOException {
Path hashCodeFilePath = headerSymlinkTreeRoot.resolve(".contents-hash");
Optional<String> currentHashCode = projectFilesystem.readFileIfItExists(hashCodeFilePath);
String newHashCode = getHeaderSymlinkTreeHashCode(resolvedContents, true, false).toString();
headerSymlinkTreesBuilder.add(headerSymlinkTreeRoot);
if (Optional.of(newHashCode).equals(currentHashCode)) {
LOG.debug(
"Symlink tree at %s is up to date, not regenerating (key %s).",
headerSymlinkTreeRoot, newHashCode);
return false;
}
LOG.debug(
"Updating symlink tree at %s (old key %s, new key %s).",
headerSymlinkTreeRoot, currentHashCode, newHashCode);
projectFilesystem.deleteRecursivelyIfExists(headerSymlinkTreeRoot);
projectFilesystem.mkdirs(headerSymlinkTreeRoot);
if (shouldCreateHeadersSymlinks) {
for (Map.Entry<Path, Path> entry : resolvedContents.entrySet()) {
Path link = entry.getKey();
Path existing = entry.getValue();
projectFilesystem.createParentDirs(link);
projectFilesystem.createSymLink(link, existing, /* force */ false);
}
}
projectFilesystem.writeContentsToPath(newHashCode, hashCodeFilePath);
return true;
}
public static void main(String[] args) {
JkLog.setHierarchicalConsoleConsumer();
//JkLog.setVerbosity(JkLog.Verbosity.VERBOSE);
JkDependencyResolver resolver = JkDependencyResolver.ofParent(JkRepo.ofMavenCentral());
JkResolveResult resolveResult = resolver.resolve(JkDependencySet.of().and("org.junit.vintage:junit-vintage-engine:jar:5.6.0"));
JkPathSequence pathSquence = resolveResult.getFiles();
Path path = Paths.get(".idea/output/test") ;
JkPathSequence classpath = JkPathSequence.of(path).and(pathSquence);
JkTestProcessor tp = JkTestProcessor.of();
tp.launch(classpath, JkTestSelection.of()
.addIncludeStandardPatterns()
.addTestClassRoots(path));
}
public void add(String templatePath, Class<?> modelClass) {
var watch = new StopWatch();
try {
Map<String, HTMLTemplate> previous = templates.putIfAbsent(templatePath, load(templatePath, modelClass));
if (previous != null) throw new Error(format("template was registered, templatePath={}", templatePath));
if (webDirectory.localEnv) {
Path path = webDirectory.path(templatePath);
templateLastModifiedTimes.put(templatePath, Files.lastModified(path));
}
} finally {
logger.info("add, templatePath={}, modelClass={}, elapsed={}", templatePath, modelClass.getCanonicalName(), watch.elapsed());
}
}
@CheckForNull
private ICodeBaseEntry createEntry(String resourceName, String moduleName) {
Path resolved = root.resolve(moduleName + "/" + resourceName);
if (Files.exists(resolved)) {
return new JrtfsCodebaseEntry(resolved, root, this);
}
return null;
}
@Test
public void testCorrectModulePatchMultiModule(Path base) throws Exception {
//note: avoiding use of java.base, as that gets special handling on some places:
Path src = base.resolve("src");
Path m1 = src.resolve("m1");
tb.writeJavaFiles(m1, "package javax.lang.model.element; public interface Extra extends Element { }");
Path m2 = src.resolve("m2");
tb.writeJavaFiles(m2, "package com.sun.source.tree; public interface Extra extends Tree { }");
Path classes = base.resolve("classes");
tb.createDirectories(classes);
String log = new JavacTask(tb)
.options("--patch-module", "java.compiler=" + m1.toString(),
"--patch-module", "jdk.compiler=" + m2.toString(),
"--module-source-path", "dummy")
.outdir(classes)
.files(findJavaFiles(src))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!log.isEmpty())
throw new Exception("expected output not found: " + log);
checkFileExists(classes, "java.compiler/javax/lang/model/element/Extra.class");
checkFileExists(classes, "jdk.compiler/com/sun/source/tree/Extra.class");
}
private static void cleanupDirectory(@Nullable Path directory) throws IOException {
if (directory == null) {
return;
}
if (Files.exists(directory)) {
try {
MoreFiles.deleteRecursively(directory, RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException e) {
throw new IOException("Cannot clean '" + directory + "'", e);
}
}
Files.createDirectories(directory);
}
private static RandomAccessFile open(Path path, FileChannel.MapMode mapMode) throws FileNotFoundException {
if (Files.notExists(path) && mapMode == FileChannel.MapMode.READ_ONLY) {
throw new FileNotFoundException(path + " does not exist");
}
final String openMode;
if (mapMode == FileChannel.MapMode.READ_ONLY) {
openMode = "r";
} else if (mapMode == FileChannel.MapMode.READ_WRITE) {
openMode = "rw";
} else {
throw new IllegalArgumentException("only MapMode.READ_ONLY and MapMode.READ_WRITE are supported");
}
return new RandomAccessFile(path.toFile(), openMode);
}
static String toString(Object holder, String serviceName, @Nullable String engineName,
@Nullable Path baseDir, @Nullable Realm realm, @Nullable String hostname,
Path docBase, @Nullable String jarRoot) {
return holder.getClass().getSimpleName() +
"(serviceName: " + serviceName +
", engineName: " + engineName +
", baseDir: " + baseDir +
", realm: " + (realm != null ? realm.getClass().getSimpleName() : "null") +
", hostname: " + hostname +
", docBase: " + docBase +
(jarRoot != null ? ", jarRoot: " + jarRoot : "") +
')';
}
private static ClassLoader createModuleLoader(final ClassLoader cl,
final String modulePath, final String addModules) {
if (addModules == null) {
throw new IllegalArgumentException("--module-path specified with no --add-modules");
}
final Path[] paths = Stream.of(modulePath.split(File.pathSeparator)).
map(s -> Paths.get(s)).
toArray(sz -> new Path[sz]);
final ModuleFinder mf = ModuleFinder.of(paths);
final Set<ModuleReference> mrefs = mf.findAll();
if (mrefs.isEmpty()) {
throw new RuntimeException("No modules in script --module-path: " + modulePath);
}
final Set<String> rootMods;
if (addModules.equals("ALL-MODULE-PATH")) {
rootMods = mrefs.stream().
map(mr->mr.descriptor().name()).
collect(Collectors.toSet());
} else {
rootMods = Stream.of(addModules.split(",")).
map(String::trim).
collect(Collectors.toSet());
}
final ModuleLayer boot = ModuleLayer.boot();
final Configuration conf = boot.configuration().
resolve(mf, ModuleFinder.of(), rootMods);
final String firstMod = rootMods.iterator().next();
return boot.defineModulesWithOneLoader(conf, cl).findLoader(firstMod);
}
public static boolean delete() {
Path file = getAccountsFile(getConfigDirectory());
try {
Files.deleteIfExists(file);
} catch (IOException e) {
logger.error("Could not delete config file in " + file.toString(), e);
return false;
}
return true;
}