下面列出了java.nio.file.Path#normalize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void addToolsJar() throws Exception {
String home = System.getProperty("java.home");
String parent = new File(home).getParent();
Path path = Paths.get(parent, "lib", "tools.jar");
path = path.normalize();
File file = path.toFile();
if (file.exists()) {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), file.toURI().toURL());
log.info("add tools.jar path:{}", path.toFile().getCanonicalPath());
} else {
if (isJava8()) {
log.error("missing tools.jar path:{}", path.toFile().getCanonicalPath());
}
}
}
/**
* Return {@code true} if paths {@code from} and {@code to} are located on same FileStore (volume or
* partition). The {@code from} must exists, while {@code to} does not have to.
*/
private static boolean areOnSameFileStore(final Path from, final Path to) {
try {
final FileStore fromStore = Files.getFileStore(from); // from must exist
Path toExistingParent = to.normalize(); // to usually does not exists, is about to be created as part of move
while (toExistingParent != null && !Files.exists(toExistingParent)) {
toExistingParent = toExistingParent.getParent();
}
if (toExistingParent != null) {
final FileStore toStore = Files.getFileStore(toExistingParent);
return fromStore.equals(toStore);
}
else {
log.warn("No ultimate parent path found for '{}'", to, new RuntimeException("marker")); // record the stack trace?
return false; // no ultimate parent? be on safe side
}
}
catch (IOException e) {
return false; // be on safe side
}
}
private static Path validateZipPathName(Path rootPath, ZipEntry entry) throws ZipException {
Path normalizedRootPath = rootPath.normalize();
Path resolved = normalizedRootPath.resolve(entry.getName()).normalize();
if (!resolved.startsWith(normalizedRootPath)) {
throw new ZipException("ZIP file contains illegal file name: " + entry.getName());
}
return resolved;
}
protected Path rootNormalizedPath()
{
Path rootPath = rootNormalizedPath;
if (rootPath == null)
{
Path path = Paths.get(root);
rootPath = rootNormalizedPath = path.normalize();
}
return rootPath;
}
/**
* Get a path without unnecessary path parts.
*
* <p>This method is a workaround for JDK-8037945 (Paths.get("").normalize() throws
* ArrayIndexOutOfBoundsException).
*/
public static Path normalize(Path path) {
if (!isEmpty(path)) {
path = path.normalize();
}
return path;
}
private IntellijPath(Path delegate) {
/*
* OpenJDK 7 on Linux has a bug which causes normalize() to throw an
* ArrayIndexOutOfBoundsException if called on the empty path.
*/
this.delegate = delegate.equals(Paths.get("")) ? delegate : delegate.normalize();
}
@Override
public HashCode getForArchiveMember(Path archiveRelativePath, Path memberPath)
throws IOException {
Path relativeFilePath = archiveRelativePath.normalize();
Preconditions.checkState(
isArchive(relativeFilePath), "%s is not an archive.", relativeFilePath);
Data data = fileSystemMap.get(relativeFilePath);
HashCode hashCode = data.getJarContentsHashes().get(memberPath);
if (hashCode == null) {
throw new NoSuchFileException(archiveRelativePath.toString());
}
return hashCode;
}
/**
* Map a file path to the equivalent name in a JAR file
*/
private static String toJarEntryName(Path file) {
Path normalized = file.normalize();
return normalized.subpath(0, normalized.getNameCount()) // drop root
.toString()
.replace(File.separatorChar, '/');
}
/**
* Tries to resolve the given path against the list of available roots.
* <p>
* If path starts with one of the listed roots, it returned back by this method, otherwise null is returned.
*/
public static Path get(Path[] roots, String path) {
for (Path root : roots) {
Path normalizedRoot = root.normalize();
Path normalizedPath = normalizedRoot.resolve(path).normalize();
if (normalizedPath.startsWith(normalizedRoot)) {
return normalizedPath;
}
}
return null;
}
/**
* Adds a reference to a project file to the generated workspace.
*
* @param path Path to the referenced project file in the repository.
*/
public void addFilePath(Path path) {
path = path.normalize();
Optional<Path> groupPath = Optional.empty();
// We skip the last name before the file name as it's usually the same as the project name, and
// adding a group would add an unnecessary level of nesting. We don't check whether it's the
// same or not to avoid inconsistent behaviour: this will result in all projects to show up in a
// group with the path of their grandparent directory in all cases.
if (path.getNameCount() > 2) {
groupPath = Optional.of(path.subpath(0, path.getNameCount() - 2));
}
addFilePath(path, groupPath);
}
public CipherFileChannel(Path path, String cipherTransformation,
SecretKeySpec secretKeySpec, Path fileSystemRoot, boolean isReverse)
throws IOException {
try {
this.path = path.normalize();
// this.encrypt =
// "encfs".equals(path.getFileSystem().provider().getScheme());
this.persistentFile = new RandomAccessFile(path.toFile(), "rw");
this.persistentChannel = this.persistentFile.getChannel();
this.isOpen = true;
this.cipherTransformation = cipherTransformation;
this.secretKeySpec = secretKeySpec;
this.relativeFilename = fileSystemRoot.relativize(this.path)
.toString();
this.isReverse = isReverse;
} catch (FileNotFoundException e) {
throw new IOException(e.getMessage(), e);
}
}
private Path checkPathIsSafe(Path pathToCheck) throws IOException {
if (Boolean.getBoolean("solr.allow.unsafe.resourceloading"))
return pathToCheck;
pathToCheck = pathToCheck.normalize();
if (pathToCheck.startsWith(instanceDir))
return pathToCheck;
throw new IOException("File " + pathToCheck + " is outside resource loader dir " + instanceDir +
"; set -Dsolr.allow.unsafe.resourceloading=true to allow unsafe loading");
}
/**
* Tries to resolve the given path against the list of available roots.
*
* If path starts with one of the listed roots, it returned back by this method, otherwise null is returned.
*/
public static Path get(Path[] roots, String path) {
for (Path root : roots) {
Path normalizedRoot = root.normalize();
Path normalizedPath = normalizedRoot.resolve(path).normalize();
if(normalizedPath.startsWith(normalizedRoot)) {
return normalizedPath;
}
}
return null;
}
private static JkDependencySet dependenciesFromImports(Path baseDir, List<String> deps) {
JkDependencySet result = JkDependencySet.of();
for (final String dependency : deps) {
if (isModuleDependencyDescription(dependency)) {
result = result.and(JkModuleDependency.of(dependency));
} else if (dependency.contains("*")) {
if (dependency.contains("*")) {
for (Path path : JkPathTree.of(baseDir).andMatching(true, dependency).getFiles()) {
result = result.andFile(path);
}
}
} else {
Path depFile = Paths.get(dependency);
if (!Files.exists(depFile)) {
final Path relativeFile = baseDir.resolve(dependency);
if (Files.exists(relativeFile)) {
depFile = relativeFile.normalize();
} else {
JkLog.warn("File '" + dependency
+ "' mentionned in @JkDefClasspath does not exist.");
}
}
result = result.andFile(depFile);
}
}
return result;
}
@Override
public HashCode getForArchiveMember(Path archiveRelativePath, Path memberPath)
throws IOException {
Path relativeFilePath = archiveRelativePath.normalize();
JarHashCodeAndFileType fileHashCodeAndFileType =
(JarHashCodeAndFileType) loadingCache.get(relativeFilePath);
HashCodeAndFileType memberHashCodeAndFileType =
fileHashCodeAndFileType.getContents().get(memberPath);
if (memberHashCodeAndFileType == null) {
throw new NoSuchFileException(archiveRelativePath.toString());
}
return memberHashCodeAndFileType.getHashCode();
}
public void setLocalRepository(Path path) throws XMLStreamException, IOException {
localRepository = path.normalize();
advertise();
}
@Test
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
Path p = Paths.get("/home/./baeldung/articles");
p = p.normalize();
assertEquals("\\home\\baeldung\\articles", p.toString());
}
static CheckoutPath createWithCheckoutDir(Path relative, Path checkoutDir) throws EvalException {
if (relative.isAbsolute()) {
throw Starlark.errorf("Absolute paths are not allowed: %s", relative);
}
return new CheckoutPath(relative.normalize(), checkoutDir);
}
/**
* Create a new PathResource from a Path handle.
* <p>Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built <i>underneath</i>
* the given root: e.g. Paths.get("C:/dir1/"), relative path "dir2" -> "C:/dir1/dir2"!
* @param path a Path handle
*/
public PathResource(Path path) {
Assert.notNull(path, "Path must not be null");
this.path = path.normalize();
}
/**
* Create a new PathResource from a Path handle.
* <p>Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built <i>underneath</i>
* the given root: e.g. Paths.get("C:/dir1/"), relative path "dir2" -> "C:/dir1/dir2"!
* @param path a Path handle
*/
public PathResource(Path path) {
Assert.notNull(path, "Path must not be null");
this.path = path.normalize();
}