java.nio.file.DirectoryNotEmptyException源码实例Demo

类java.nio.file.DirectoryNotEmptyException源码实例Demo

下面列出了java.nio.file.DirectoryNotEmptyException 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Flink-CEPplus   文件: LocalFileSystem.java
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
	final File srcFile = pathToFile(src);
	final File dstFile = pathToFile(dst);

	final File dstParent = dstFile.getParentFile();

	// Files.move fails if the destination directory doesn't exist
	//noinspection ResultOfMethodCallIgnored -- we don't care if the directory existed or was created
	dstParent.mkdirs();

	try {
		Files.move(srcFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
		return true;
	}
	catch (NoSuchFileException | AccessDeniedException | DirectoryNotEmptyException | SecurityException ex) {
		// catch the errors that are regular "move failed" exceptions and return false
		return false;
	}
}
 
源代码2 项目: flink   文件: LocalFileSystem.java
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
	final File srcFile = pathToFile(src);
	final File dstFile = pathToFile(dst);

	final File dstParent = dstFile.getParentFile();

	// Files.move fails if the destination directory doesn't exist
	//noinspection ResultOfMethodCallIgnored -- we don't care if the directory existed or was created
	dstParent.mkdirs();

	try {
		Files.move(srcFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
		return true;
	}
	catch (NoSuchFileException | AccessDeniedException | DirectoryNotEmptyException | SecurityException ex) {
		// catch the errors that are regular "move failed" exceptions and return false
		return false;
	}
}
 
源代码3 项目: public   文件: SwengShell.java
@Override
public void remove(String fileOrDirName) throws NoSuchFileException, DirectoryNotWriteableException, FileNotWriteableException, DirectoryNotEmptyException {
    if (!isBasename(fileOrDirName)) {
        throw new IllegalArgumentException();
    }
    String path = currentWorkingDirectory + "/" + fileOrDirName;

    FileSystemNode c = currentFs.getChild(fileOrDirName);
    boolean isWriteable = c.getPermissions().matches(".w");
    boolean isFile = c.isFile();
    boolean isEmptyDirectory = !isFile && c.getChildrenNames().size() == 0;

    if (isFile && !isWriteable) throw new FileNotWriteableException(path);
    if (!isFile && !isWriteable) throw new DirectoryNotWriteableException(path);

    // Bug 2:
    // bug => if (!isFile && isWriteable && isEmptyDirectory)
    // fix => if (!isFile && isWriteable && !isEmptyDirectory)
    if (!isFile && isWriteable && !isEmptyDirectory) throw new DirectoryNotEmptyException(path);

    if (isFile || isEmptyDirectory) {
        c.getParent().removeChild(fileOrDirName);
    }
}
 
源代码4 项目: public   文件: GradedAppTest.java
@GradedTest("Bug 2")
void t02_testRemoveDirectoryNonEmpty() throws NoSuchPathException, DirectoryNotReadableException {
    sh.changeDirectory("/");
    // Removing non-empty directory
    assertThrows(DirectoryNotEmptyException.class, () -> sh.remove("d_b"));

    sh.changeDirectory("/d_b/d_d");
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
            "f_i.txt",
            "f_j.txt",
            "d_e"
    ));

    // Removing empty directory
    assertDoesNotThrow(() -> sh.remove("d_e"));
}
 
源代码5 项目: public   文件: AppTest.java
@Test
void testRemoveFiles() throws NoSuchPathException, DirectoryNotReadableException, DirectoryNotWriteableException, DirectoryNotEmptyException, NoSuchFileException, FileNotWriteableException {
    sh.changeDirectory("/");
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
            "f_a.txt",
            "f_b.txt",
            "d_a",
            "d_b"
    ));

    sh.remove("f_a.txt");
    sh.remove("f_b.txt");
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
            "d_a",
            "d_b"
    ));
}
 
源代码6 项目: public   文件: AppTest.java
@Test
void testRemoveDirectoryNonEmpty() throws NoSuchPathException, DirectoryNotReadableException {
    sh.changeDirectory("/");
    // Removing non-empty directory
    assertThrows(DirectoryNotEmptyException.class, () -> sh.remove("d_b"));

    sh.changeDirectory("/d_b/d_d");
    assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
            "f_i.txt",
            "f_j.txt",
            "d_e"
    ));

    // Removing empty directory
    assertDoesNotThrow(() -> sh.remove("d_e"));
}
 
源代码7 项目: public   文件: SwengShell.java
@Override
public void remove(String fileOrDirName) throws NoSuchFileException, DirectoryNotWriteableException, FileNotWriteableException, DirectoryNotEmptyException {
    if (!isBasename(fileOrDirName)) {
        throw new IllegalArgumentException();
    }
    String path = currentWorkingDirectory + "/" + fileOrDirName;

    FileSystemNode c = currentFs.getChild(fileOrDirName);
    boolean isWriteable = c.getPermissions().matches(".w");
    boolean isFile = c.isFile();
    boolean isEmptyDirectory = !isFile && c.getChildrenNames().size() == 0;

    if (isFile && !isWriteable) throw new FileNotWriteableException(path);
    if (!isFile && !isWriteable) throw new DirectoryNotWriteableException(path);

    if (!isFile && isWriteable && isEmptyDirectory) throw new DirectoryNotEmptyException(path);

    if (isFile || isEmptyDirectory) {
        c.getParent().removeChild(fileOrDirName);
    }
}
 
源代码8 项目: mycore   文件: MCRFileSystemProvider.java
@Override
public void delete(Path path) throws IOException {
    MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path);
    MCRStoredNode child = MCRFileSystemUtils.resolvePath(mcrPath);
    if (child instanceof MCRDirectory) {
        if (child.hasChildren()) {
            throw new DirectoryNotEmptyException(mcrPath.toString());
        }
    }
    try {
        child.delete();
        MCRPathEventHelper.fireFileDeleteEvent(path);
    } catch (RuntimeException e) {
        throw new IOException("Could not delete: " + mcrPath, e);
    }
}
 
源代码9 项目: mycore   文件: MCRIFSFileSystem.java
@Override
public void removeRoot(String owner) throws FileSystemException {
    MCRPath rootPath = getPath(owner, "", this);
    MCRDirectory rootDirectory = MCRDirectory.getRootDirectory(owner);
    if (rootDirectory == null) {
        throw new NoSuchFileException(rootPath.toString());
    }
    if (rootDirectory.isDeleted()) {
        return;
    }
    if (rootDirectory.hasChildren()) {
        throw new DirectoryNotEmptyException(rootPath.toString());
    }
    try {
        rootDirectory.delete();
    } catch (RuntimeException e) {
        LogManager.getLogger(getClass()).warn("Catched run time exception while removing root directory.", e);
        throw new FileSystemException(rootPath.toString(), null, e.getMessage());
    }
    LogManager.getLogger(getClass()).info("Removed root directory: {}", rootPath);
}
 
源代码10 项目: incubator-taverna-language   文件: TestBundles.java
@Test(expected = DirectoryNotEmptyException.class)
public void safeCopyFails() throws Exception {
	Path tmp = Files.createTempDirectory("test");
	tmp.toFile().deleteOnExit();
	Path f1 = tmp.resolve("f1");
	f1.toFile().deleteOnExit();
	Path d1 = tmp.resolve("d1");
	d1.toFile().deleteOnExit();
	Files.createFile(f1);

	// Make d1 difficult to overwrite
	Files.createDirectory(d1);
	Files.createFile(d1.resolve("child"));

	try {
		// Files.copy(f1, d1, StandardCopyOption.REPLACE_EXISTING);
		Bundles.safeCopy(f1, d1);
	} finally {
		assertEquals(Arrays.asList("d1", "f1"), ls(tmp));
		assertTrue(Files.exists(f1));
		assertTrue(Files.isDirectory(d1));
	}
}
 
源代码11 项目: CodeDefenders   文件: FileUtils.java
/**
 * Stores a file for given parameters on the hard drive.
 *
 * @param folderPath  The path of the folder the file will be stored in as a {@link Path}. The folder must not
 *                    already exist.
 * @param fileName    The file name (e.g. {@code MyClass.java}).
 * @param fileContent The actual file content.
 * @return The path of the newly stored file.
 * @throws IOException when storing the file fails.
 */
public static Path storeFile(Path folderPath, String fileName, String fileContent) throws IOException {

    final Path filePath = folderPath.resolve(fileName);
    try {
        Files.createDirectories(folderPath);
        final Path path = Files.createFile(filePath);
        Files.write(path, fileContent.getBytes());
        return path;
    } catch (IOException e) {
        logger.error("Could not store file.", e);
        try {
            // removing folder again, if empty
            Files.delete(folderPath);
        } catch (DirectoryNotEmptyException ignored) {
        }
        throw e;
    }
}
 
源代码12 项目: flink   文件: LocalFileSystem.java
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
	final File srcFile = pathToFile(src);
	final File dstFile = pathToFile(dst);

	final File dstParent = dstFile.getParentFile();

	// Files.move fails if the destination directory doesn't exist
	//noinspection ResultOfMethodCallIgnored -- we don't care if the directory existed or was created
	dstParent.mkdirs();

	try {
		Files.move(srcFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
		return true;
	}
	catch (NoSuchFileException | AccessDeniedException | DirectoryNotEmptyException | SecurityException ex) {
		// catch the errors that are regular "move failed" exceptions and return false
		return false;
	}
}
 
源代码13 项目: jsr203-hadoop   文件: TestFileSystem.java
@Test(expected = DirectoryNotEmptyException.class)
public void testDirectoryNotEmptyExceptionOnDelete()
    throws URISyntaxException, IOException {
  // Create the directory
  URI uriDir = clusterUri
      .resolve("/tmp/testDirectoryNotEmptyExceptionOnDelete");
  Path pathDir = Paths.get(uriDir);
  // Check that directory doesn't exists
  if (Files.exists(pathDir)) {
    Files.delete(pathDir);
  }

  Files.createDirectory(pathDir);
  assertTrue(Files.exists(pathDir));
  // Create the file
  Path path = pathDir.resolve("test_file");
  Files.createFile(path);
  assertTrue(Files.exists(path));

  Files.delete(pathDir); // this one generate the exception
  assertFalse(Files.exists(path));

}
 
源代码14 项目: jsr203-hadoop   文件: TestFiles.java
/**
 * Test for
 * {@link Files#createDirectories(Path, java.nio.file.attribute.FileAttribute...)
 * Files.createDirectories()}.
 * 
 * @throws IOException
 */
@Test(expected = DirectoryNotEmptyException.class)
public void testCreateDirectories() throws IOException {
  Path rootPath = Paths.get(clusterUri);

  Path dir = rootPath.resolve(rootPath.resolve("tmp/1/2/3/4/5"));

  Path dir2 = Files.createDirectories(dir);
  assertTrue(Files.exists(dir2));

  Files.delete(rootPath.resolve("tmp/1/2/3/4/5"));
  Files.delete(rootPath.resolve("tmp/1/2/3/4"));
  Files.delete(rootPath.resolve("tmp/1/2/3"));
  Files.delete(rootPath.resolve("tmp/1/2"));
  // Throws
  Files.delete(rootPath.resolve("tmp"));
}
 
@Test
public void testDeleteNotRecursive_shouldBeAppliedToHierarchyOfDirectories()
    throws IOException, URISyntaxException {
  Configuration config = GoogleHadoopFileSystemIntegrationHelper.getTestConfig();
  GoogleHadoopFS ghfs = new GoogleHadoopFS(initUri, config);

  FsPermission permission = new FsPermission("000");

  URI parentDir = initUri.resolve("/testDeleteRecursive_shouldDeleteAllInPath");
  Path testDir = new Path(parentDir.resolve("test_dir").toString());

  ghfs.mkdir(testDir, permission, /* createParent= */ true);

  assertThrows(
      DirectoryNotEmptyException.class,
      () -> ghfs.delete(testDir.getParent(), /* recursive= */ false));
}
 
源代码16 项目: TerasologyLauncher   文件: TestFileUtils.java
@Test
public void testDeleteFileSilentlyWithNonEmptyDirectory() throws IOException {
    Path tempFile = tempFolder.resolve(FILE_NAME);
    Files.createFile(tempFile);
    assertTrue(Files.exists(tempFile));

    // DirectoryNotEmptyException will be logged but not thrown
    var loggedException = TestLoggers.sys().expect("", Level.ERROR,
            LogMatchers.hasMatchingExtraThrowable(Matchers.instanceOf(DirectoryNotEmptyException.class))
    );

    FileUtils.deleteFileSilently(tempFolder);

    assertTrue(Files.exists(tempFolder));
    loggedException.assertObservation();
}
 
源代码17 项目: Quelea   文件: RecordingEncoder.java
public RecordingEncoder(String mediaUrl, String[] options) {
    this.options = options;
    this.mediaPath = mediaUrl;
    new NativeDiscovery().discover();
    mp = new EmbeddedMediaPlayerComponent() {

        @Override
        public void finished(MediaPlayer mediaPlayer) {
            // Delete the WAV file when convertion is done
            String error;
            Path path = Paths.get(mediaUrl);
            do {
                try {
                    Files.delete(path);
                    error = "";
                    mediaPlayer.release();
                } catch (NoSuchFileException | DirectoryNotEmptyException x) {
                    error = "";
                } catch (IOException x) {
                    // File is still being read by the system,
                    // keep trying to delete until it's avaiable again.
                    error = "busy";
                }
            } while (!error.equals(""));
            if (statusPanel != null) {
                Platform.runLater(() -> {
                    statusPanel.done();
                });
            }
            converting = false;
        }
    };
    
    // Set up VLC window
    ourFrame.setContentPane(mp);
    ourFrame.setSize(1, 1);
    ourFrame.setVisible(true);
    ourFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
 
源代码18 项目: football-events   文件: StreamsTester.java
public void close() throws IOException {
    if (testDriver != null) {
        try {
            testDriver.close();
        } catch (StreamsException e) {
            // temporary workaround for https://github.com/apache/kafka/pull/4713
            if (!(e.getCause() instanceof DirectoryNotEmptyException)) {
                throw e;
            }
        }
    }
    FileSystemUtils.deleteRecursively(kafkaTempDir);
}
 
源代码19 项目: aws-sdk-java-v2   文件: ResponseTransformer.java
/**
 * Creates a response transformer that writes all response content to the specified file. If the file already exists
 * then a {@link java.nio.file.FileAlreadyExistsException} will be thrown.
 *
 * @param path        Path to file to write to.
 * @param <ResponseT> Type of unmarshalled response POJO.
 * @return ResponseTransformer instance.
 */
static <ResponseT> ResponseTransformer<ResponseT, ResponseT> toFile(Path path) {
    return (resp, in) -> {
        try {
            InterruptMonitor.checkInterrupted();
            Files.copy(in, path);
            return resp;
        } catch (IOException copyException) {
            String copyError = "Failed to read response into file: " + path;

            // If the write failed because of the state of the file, don't retry the request.
            if (copyException instanceof FileAlreadyExistsException || copyException instanceof DirectoryNotEmptyException) {
                throw new IOException(copyError, copyException);
            }

            // Try to clean up the file so that we can retry the request. If we can't delete it, don't retry the request.
            try {
                Files.deleteIfExists(path);
            } catch (IOException deletionException) {
                Logger.loggerFor(ResponseTransformer.class)
                      .error(() -> "Failed to delete destination file '" + path +
                                   "' after reading the service response " +
                                   "failed.", deletionException);

                throw new IOException(copyError + ". Additionally, the file could not be cleaned up (" +
                                      deletionException.getMessage() + "), so the request will not be retried.",
                                      copyException);
            }

            // Retry the request
            throw RetryableException.builder().message(copyError).cause(copyException).build();
        }
    };
}
 
源代码20 项目: mycore   文件: MCRFileSystemProvider.java
@Override
public void delete(Path path) throws IOException {
    MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path);
    MCRFilesystemNode child = resolvePath(mcrPath);
    if (child instanceof MCRDirectory) {
        if (((MCRDirectory) child).hasChildren()) {
            throw new DirectoryNotEmptyException(mcrPath.toString());
        }
    }
    try {
        child.delete();
    } catch (RuntimeException e) {
        throw new IOException("Could not delete: " + mcrPath, e);
    }
}
 
源代码21 项目: sftp-fs   文件: SFTPFileSystem.java
void move(SFTPPath source, SFTPPath target, CopyOption... options) throws IOException {
    boolean sameFileSystem = haveSameFileSystem(source, target);
    CopyOptions copyOptions = CopyOptions.forMove(sameFileSystem, options);

    try (Channel channel = channelPool.get()) {
        if (!sameFileSystem) {
            SftpATTRS attributes = getAttributes(channel, source, false);
            if (attributes.isLink()) {
                throw new IOException(SFTPMessages.copyOfSymbolicLinksAcrossFileSystemsNotSupported());
            }
            copyAcrossFileSystems(channel, source, attributes, target, copyOptions);
            channel.delete(source.path(), attributes.isDir());
            return;
        }

        try {
            if (isSameFile(channel, source, target)) {
                // non-op, don't do a thing as specified by Files.move
                return;
            }
        } catch (@SuppressWarnings("unused") NoSuchFileException e) {
            // the source or target does not exist or either path is an invalid link
            // call getAttributes to ensure the source file exists
            // ignore any error to target or if the source link is invalid
            getAttributes(channel, source, false);
        }

        if (toAbsolutePath(source).parentPath() == null) {
            // cannot move or rename the root
            throw new DirectoryNotEmptyException(source.path());
        }

        SftpATTRS targetAttributes = findAttributes(channel, target, false);
        if (copyOptions.replaceExisting && targetAttributes != null) {
            channel.delete(target.path(), targetAttributes.isDir());
        }

        channel.rename(source.path(), target.path());
    }
}
 
源代码22 项目: sftp-fs   文件: SFTPFileSystemTest.java
@Test
public void testMoveEmptyRoot() {

    CopyOption[] options = {};
    DirectoryNotEmptyException exception = assertThrows(DirectoryNotEmptyException.class,
            () -> fileSystem.move(createPath("/"), createPath("/baz"), options));
    assertEquals("/", exception.getFile());

    assertFalse(Files.exists(getPath("/baz")));
}
 
源代码23 项目: sftp-fs   文件: SFTPFileSystemTest.java
@Test
public void testMoveNonEmptyRoot() throws IOException {
    addDirectory("/foo");

    CopyOption[] options = {};
    DirectoryNotEmptyException exception = assertThrows(DirectoryNotEmptyException.class,
            () -> fileSystem.move(createPath("/"), createPath("/baz"), options));
    assertEquals("/", exception.getFile());

    assertTrue(Files.isDirectory(getPath("/foo")));
    assertFalse(Files.exists(getPath("/baz")));
}
 
private void cleanDir(File rootDir) throws IOException {
  if(rootDir.isDirectory()) {
    try {
      Files.delete(Paths.get(rootDir.toURI()));
    } catch (DirectoryNotEmptyException dne) {
      for(File f : rootDir.listFiles()) {
        cleanDir(f);
      }
      rootDir.delete();
    }
  }
  else {
    rootDir.delete();
  }
}
 
源代码25 项目: agrona   文件: IoUtilTest.java
@Test
void deleteIfExistsFailsOnNonEmptyDirectory() throws IOException
{
    final Path dir = tempDir.resolve("dir");
    Files.createDirectory(dir);
    Files.createFile(dir.resolve("file.txt"));

    assertThrows(DirectoryNotEmptyException.class, () -> IoUtil.deleteIfExists(dir.toFile()));
}
 
源代码26 项目: agrona   文件: IoUtilTest.java
@Test
void deleteIfExistsErrorHandlerFailsOnNonEmptyDirectory() throws IOException
{
    final ErrorHandler errorHandler = mock(ErrorHandler.class);
    final Path dir = tempDir.resolve("dir");
    Files.createDirectory(dir);
    Files.createFile(dir.resolve("file.txt"));

    IoUtil.deleteIfExists(dir.toFile(), errorHandler);

    verify(errorHandler).onError(isA(DirectoryNotEmptyException.class));
}
 
源代码27 项目: jsr203-hadoop   文件: HadoopFileSystem.java
public void deleteFile(org.apache.hadoop.fs.Path hadoopPath, boolean failIfNotExists)
      throws IOException
  {
checkWritable();

// If no exist
if (!this.fs.exists(hadoopPath))
{
	if (failIfNotExists)
		throw new NoSuchFileException(hadoopPath.toString());
}
else
{
	FileStatus stat = this.fs.getFileStatus(hadoopPath);
	if (stat.isDirectory()) {
		FileStatus[] stats = this.fs.listStatus(hadoopPath);
		if (stats.length > 0)
			throw new DirectoryNotEmptyException(hadoopPath.toString());
	}
	// Try to delete with no recursion
	this.fs.delete(hadoopPath, false);
}

      /*IndexNode inode = getInode(hadoopPath);
      if (inode == null) {
          if (hadoopPath != null && hadoopPath.length == 0)
              throw new ZipException("root directory </> can't not be delete");
          if (failIfNotExists)
              throw new NoSuchFileException(getString(hadoopPath));
      } else {
          if (inode.isDir() && inode.child != null)
              throw new DirectoryNotEmptyException(getString(hadoopPath));
          updateDelete(inode);
      }*/
  }
 
源代码28 项目: jsch-nio   文件: UnixSshFileSystemProvider.java
private void delete( UnixSshPath path, BasicFileAttributes attributes ) throws IOException {
    if ( attributes.isDirectory() ) {
        if ( execute( path, path.getFileSystem().getCommand( "rmdir" ) 
                + " " + path.toAbsolutePath().quotedString() )
                .getExitCode() != 0 ) {
            throw new DirectoryNotEmptyException( path.toString() );
        }
    }
    else {
        executeForStdout( path, path.getFileSystem().getCommand( "unlink" ) 
                + " " + path.toAbsolutePath().quotedString() );
    }
}
 
源代码29 项目: buck   文件: RmStepTest.java
@Test
public void nonRecursiveModeFailsOnDirectories() throws Exception {
  Path dir = createNonEmptyDirectory();

  RmStep step =
      RmStep.of(
          BuildCellRelativePath.fromCellRelativePath(filesystem.getRootPath(), filesystem, dir));
  thrown.expect(DirectoryNotEmptyException.class);
  step.execute(context);
}
 
源代码30 项目: simple-nfs   文件: LocalFileSystem.java
@Override
public void remove(Inode parent, String path) throws IOException {
    long parentInodeNumber = getInodeNumber(parent);
    Path parentPath = resolveInode(parentInodeNumber);
    Path targetPath = parentPath.resolve(path);
    long targetInodeNumber = resolvePath(targetPath);
    try {
        Files.delete(targetPath);
    } catch (DirectoryNotEmptyException e) {
        throw new NotEmptyException("dir " + targetPath + " is note empty", e);
    }
    unmap(targetInodeNumber, targetPath);
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法