下面列出了java.nio.file.Path#getParent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static boolean initProfiles() {
// check if ct.sym exists; if not use the profiles.properties file
Path home = Paths.get(System.getProperty("java.home"));
if (home.endsWith("jre")) {
home = home.getParent();
}
Path ctsym = home.resolve("lib").resolve("ct.sym");
boolean symbolExists = ctsym.toFile().exists();
if (!symbolExists) {
Path testSrcProfiles =
Paths.get(System.getProperty("test.src", "."), "profiles.properties");
if (!testSrcProfiles.toFile().exists())
throw new Error(testSrcProfiles + " does not exist");
System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n",
ctsym, testSrcProfiles);
System.setProperty("jdeps.profiles", testSrcProfiles.toString());
}
return symbolExists;
}
private static boolean initProfiles() {
// check if ct.sym exists; if not use the profiles.properties file
Path home = Paths.get(System.getProperty("java.home"));
if (home.endsWith("jre")) {
home = home.getParent();
}
Path ctsym = home.resolve("lib").resolve("ct.sym");
boolean symbolExists = ctsym.toFile().exists();
if (!symbolExists) {
Path testSrcProfiles =
Paths.get(System.getProperty("test.src", "."), "profiles.properties");
if (!testSrcProfiles.toFile().exists())
throw new Error(testSrcProfiles + " does not exist");
System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n",
ctsym, testSrcProfiles);
System.setProperty("jdeps.profiles", testSrcProfiles.toString());
}
return symbolExists;
}
public static void unzip(Path zipFilePath, Path destDir) throws IOException {
try (ZipFile zipFile = new ZipFile(zipFilePath.toString())) {
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry zipEntry = e.nextElement();
String name = zipEntry.getName();
Path path = destDir.resolve(name);
if (name.endsWith("/")) { // if (Files.isDirectory(path)) {
LOGGER.info(() -> String.format("mkdir1: %s", path));
Files.createDirectories(path);
} else {
Path parent = path.getParent();
// if (Objects.nonNull(parent) && Files.notExists(parent)) { // noticeably poor performance in JDK 8
if (Objects.nonNull(parent) && !parent.toFile().exists()) {
LOGGER.info(() -> String.format("mkdir2: %s", parent));
Files.createDirectories(parent);
}
LOGGER.info(() -> String.format("copy: %s", path));
Files.copy(zipFile.getInputStream(zipEntry), path, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
private static Path ensureFileHasSuffix(final Path file, final String suffix) {
String filename = filename(file);
if (!filename.contains(".")) {
String newFilename = filename + suffix;
Path parent = file.getParent();
if (parent == null) {
return Paths.get(newFilename);
} else {
return parent.resolve(newFilename);
}
}
return file;
}
private static List<Path> unzip(Path jarFile, Path destDir, Predicate<JarEntry> filter) throws IOException {
List<Path> result = new ArrayList<>();
try (JarFile agentJar = new JarFile(jarFile.toFile())) {
Enumeration<JarEntry> jarEntries = agentJar.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
if (filter.test(jarEntry)) {
Path destFile = destDir.resolve(jarEntry.getName());
if (!destFile.getParent().toFile().exists()) {
if (!destFile.getParent().toFile().mkdirs()) {
throw new IOException("Failed to make directory: " + destFile.getParent());
}
}
Files.copy(agentJar.getInputStream(jarEntry), destFile);
result.add(destFile);
}
}
}
return result;
}
/**
* Creates an instance of {@link FileWatcher} to watch the given file.
*
* @param watchFile file to be watched
* @throws FileWatcherException thrown when error on creating an instance of {@link FileWatcher}
*/
public FileWatcher(Path watchFile) throws FileWatcherException {
// Do not allow this to be a folder since we want to watch files
if (!Files.isRegularFile(watchFile)) {
throw new FileWatcherException(StringUtil.concatStrings(watchFile, " is not a regular file."));
}
// This is always a folder
this.folderPath = watchFile.getParent();
if (this.folderPath == null) {
throw new FileWatcherException("The path provided do not have a parent. Please provide to complete " +
"path to the file.");
}
// Keep this relative to the watched folder
Path watchFileName = watchFile.getFileName();
if (watchFileName == null) {
throw new FileWatcherException("The path has 0 (zero) elements. Please provide a valid file path.");
}
this.watchFile = watchFileName.toString();
}
private static boolean initProfiles() {
// check if ct.sym exists; if not use the profiles.properties file
Path home = Paths.get(System.getProperty("java.home"));
if (home.endsWith("jre")) {
home = home.getParent();
}
Path ctsym = home.resolve("lib").resolve("ct.sym");
boolean symbolExists = ctsym.toFile().exists();
if (!symbolExists) {
Path testSrcProfiles =
Paths.get(System.getProperty("test.src", "."), "profiles.properties");
if (!testSrcProfiles.toFile().exists())
throw new Error(testSrcProfiles + " does not exist");
System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n",
ctsym, testSrcProfiles);
System.setProperty("jdeps.profiles", testSrcProfiles.toString());
}
return symbolExists;
}
/** @param path the absolute path of the directory to create */
private static void mkdirImpl(Path path) throws IOException {
path.toFile().mkdirs();
if (!path.toFile().exists()) {
// it could be that relative has a parent that used to be a symlink, but now is not anymore...
boolean foundOldSymlink = false;
Path current = path;
while (current != null) {
if (Files.isSymbolicLink(current)) {
current.toFile().delete();
path.toFile().mkdirs();
foundOldSymlink = true;
}
current = current.getParent();
}
if (!foundOldSymlink) {
throw new IOException("Could not create directory " + path + " (" + path.toFile() + " does not exist)");
}
}
}
public static Path getParentOrEmpty(Path path) {
Path parent = path.getParent();
if (parent == null) {
parent = emptyOf(path);
}
return parent;
}
private static boolean shouldRecord(Set<Path> outputs, Path path) {
Path parent = path.getParent();
while (parent != null) {
if (outputs.contains(parent)) {
return false;
}
parent = parent.getParent();
}
return true;
}
private boolean isParentWritable(Path path) {
Path parent = path.getParent();
if (parent == null) {
parent = path.toAbsolutePath().getParent();
}
return parent != null && Files.isWritable(parent);
}
/**
* Copies the source file to the target file.
*
* @param aSourceFile
* The source file to use. May not be <code>null</code>. Needs to be an
* existing file.
* @param aTargetFile
* The destination files. May not be <code>null</code> and may not be
* an existing file.
* @return A non-<code>null</code> error code.
*/
@Nonnull
public static FileIOError copyFile (@Nonnull final Path aSourceFile, @Nonnull final Path aTargetFile)
{
ValueEnforcer.notNull (aSourceFile, "SourceFile");
ValueEnforcer.notNull (aTargetFile, "TargetFile");
final Path aRealSourceFile = _getUnifiedPath (aSourceFile);
final Path aRealTargetFile = _getUnifiedPath (aTargetFile);
// Does the source file exist?
if (!aRealSourceFile.toFile ().isFile ())
return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError (EFileIOOperation.COPY_FILE, aRealSourceFile);
// Are source and target different?
if (EqualsHelper.equals (aRealSourceFile, aRealTargetFile))
return EFileIOErrorCode.SOURCE_EQUALS_TARGET.getAsIOError (EFileIOOperation.COPY_FILE, aRealSourceFile);
// Does the target file already exist?
if (aRealTargetFile.toFile ().exists ())
return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError (EFileIOOperation.COPY_FILE, aRealTargetFile);
// Is the source file readable?
if (!Files.isReadable (aRealSourceFile))
return EFileIOErrorCode.SOURCE_NOT_READABLE.getAsIOError (EFileIOOperation.COPY_FILE, aRealSourceFile);
// Is the target parent directory writable?
final Path aTargetParentDir = aRealTargetFile.getParent ();
if (aTargetParentDir != null && aTargetParentDir.toFile ().exists () && !Files.isWritable (aTargetParentDir))
return EFileIOErrorCode.TARGET_PARENT_NOT_WRITABLE.getAsIOError (EFileIOOperation.COPY_FILE, aRealTargetFile);
// Ensure the targets parent directory is present
PathHelper.ensureParentDirectoryIsPresent (aRealTargetFile);
return _perform (EFileIOOperation.COPY_FILE, Files::copy, aRealSourceFile, aRealTargetFile);
}
private void testStartsWith(Path path) {
// empty path doesn't start with any path
if (root != null || !names.isEmpty()) {
Path other = path;
while (other != null) {
assertTrue(path + ".startsWith(" + other + ") should be true", path.startsWith(other));
assertTrue(
path + ".startsWith(" + other + ") should be true", path.startsWith(other.toString()));
other = other.getParent();
}
}
}
private boolean isParentWritable(Path path) {
Path parent = path.getParent();
if (parent == null) {
parent = path.toAbsolutePath().getParent();
}
return parent != null && Files.isWritable(parent);
}
@Override
public void setCurrentFolder( Path currentFolder ) {
while ( currentFolder != null && !Files.exists( currentFolder ) )
currentFolder = currentFolder.getParent();
if ( currentFolder != null )
setCurrentDirectory( currentFolder.toFile() );
}
private static void copyFile(File f) {
try {
Path classFilePath = Paths.get(classFile);
String packagePath = classFilePath.getParent() == null ? "" : classFilePath.getParent().toString();
Path p = Paths.get(destinationDir + packagePath + File.separator + f.getName());
Files.createDirectories(p.getParent());
try (InputStream is = new FileInputStream(f)) {
Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ex) {
throw new RuntimeException("Could not copy file " + f, ex);
}
}
private Iterator<Path> getUncompressedLogrotatedFileIterator(
SingularityExecutorTaskDefinition taskDefinition
) {
final Path serviceLogOutPath = taskDefinition.getServiceLogOutPath();
final Path parent = serviceLogOutPath.getParent();
if (parent == null) {
throw new IllegalStateException(
"Service log path " + serviceLogOutPath + " has no parent"
);
}
final Path logrotateToPath = parent.resolve(
executorConfiguration.getLogrotateToDirectory()
);
if (!logrotateToPath.toFile().exists() || !logrotateToPath.toFile().isDirectory()) {
LOG.warn(
"Skipping uncompressed logrotated file cleanup for {} -- {} does not exist or is not a directory (task sandbox was probably garbage collected by Mesos)",
taskDefinition.getTaskId(),
logrotateToPath
);
return Collections.emptyIterator();
}
try {
DirectoryStream<Path> dirStream = Files.newDirectoryStream(
logrotateToPath,
String.format("%s-*", serviceLogOutPath.getFileName())
);
return dirStream.iterator();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Creates a command line classpath of the dependent jar libraries
*
* @return concatenated string suitable for -d command line option
*/
public static String getLibraryClassPath()
{
URL currentURL = Creator.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println("Current URL:" + currentURL.toString());
Path currentPath = null;
try
{
currentPath = new File(currentURL.toURI()).toPath();
}
catch(Exception e)
{
mLog.error("Error discovering current execution path to lookup compile dependencies", e);
currentPath = null;
}
if(currentPath != null && Files.exists(currentPath))
{
System.out.println("Discovering: Current Location [" + currentPath.toString() + "]");
Path parent = currentPath.getParent();
System.out.println("Discovering: Compile Dependencies [" + parent.toString() + "]");
StringJoiner joiner = new StringJoiner(String.valueOf(File.pathSeparatorChar));
try
{
DirectoryStream<Path> stream = Files.newDirectoryStream(parent);
stream.forEach(path -> {
if(!Files.isDirectory(path) && path.toString().endsWith("jar"))
{
joiner.add(path.toString());
}
});
}
catch(IOException ioe)
{
System.out.println("Failed: Error creating classpath for compile-time libraries - " +
ioe.getLocalizedMessage());
ioe.printStackTrace();
System.exit(EXIT_CODE_IO_ERROR);
}
return joiner.toString();
}
return "";
}
StorageAsset getFile(String path) throws IOException {
Path filePath = Paths.get(path);
FilesystemStorage filesystemStorage = new FilesystemStorage(filePath.getParent(), new DefaultFileLockManager());
return new FilesystemAsset(filesystemStorage, filePath.getFileName().toString(), filePath);
}
/**
* Sets the contents of the file at the given path and creates all parent
* directories in our mocked view of the file system. If a compression is
* chosen, the file contents is the compressed version of the given
* contents. Strings are encoded as UTF8.
* <p>
* This method is used for mocking and is always successful, even if the
* object is in read-only mode otherwise.
*
* @param path
* @param contents
* @param compressionType
* @throws IOException
*/
public void setFileContents(Path path, String contents,
CompressionType compressionType) throws IOException {
files.put(path, MockStringContentFactory.getBytesFromString(contents,
compressionType));
Path parent = path.getParent();
if (parent != null) {
setFileContents(parent, DIRECTORY_MARKER_STRING);
}
}