java.nio.file.DirectoryNotEmptyException Java Examples
The following examples show how to use
java.nio.file.DirectoryNotEmptyException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalFileSystem.java From flink with Apache License 2.0 | 6 votes |
@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; } }
Example #2
Source File: TestFileUtils.java From TerasologyLauncher with Apache License 2.0 | 6 votes |
@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(); }
Example #3
Source File: GoogleHadoopFSIntegrationTest.java From hadoop-connectors with Apache License 2.0 | 6 votes |
@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)); }
Example #4
Source File: TestFiles.java From jsr203-hadoop with Apache License 2.0 | 6 votes |
/** * 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")); }
Example #5
Source File: TestFileSystem.java From jsr203-hadoop with Apache License 2.0 | 6 votes |
@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)); }
Example #6
Source File: LocalFileSystem.java From flink with Apache License 2.0 | 6 votes |
@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; } }
Example #7
Source File: FileUtils.java From CodeDefenders with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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; } }
Example #8
Source File: TestBundles.java From incubator-taverna-language with Apache License 2.0 | 6 votes |
@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)); } }
Example #9
Source File: MCRIFSFileSystem.java From mycore with GNU General Public License v3.0 | 6 votes |
@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); }
Example #10
Source File: MCRFileSystemProvider.java From mycore with GNU General Public License v3.0 | 6 votes |
@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); } }
Example #11
Source File: LocalFileSystem.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
@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; } }
Example #12
Source File: SwengShell.java From public with Apache License 2.0 | 6 votes |
@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); } }
Example #13
Source File: AppTest.java From public with Apache License 2.0 | 6 votes |
@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")); }
Example #14
Source File: SwengShell.java From public with Apache License 2.0 | 6 votes |
@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); } }
Example #15
Source File: AppTest.java From public with Apache License 2.0 | 6 votes |
@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" )); }
Example #16
Source File: GradedAppTest.java From public with Apache License 2.0 | 6 votes |
@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")); }
Example #17
Source File: ConfigurationManagerIntegrationTest.java From metron with Apache License 2.0 | 5 votes |
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(); } }
Example #18
Source File: LocalFileSystem.java From simple-nfs with Apache License 2.0 | 5 votes |
@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); }
Example #19
Source File: RmStepTest.java From buck with Apache License 2.0 | 5 votes |
@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); }
Example #20
Source File: UnixSshFileSystemProvider.java From jsch-nio with MIT License | 5 votes |
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() ); } }
Example #21
Source File: RecordingEncoder.java From Quelea with GNU General Public License v3.0 | 5 votes |
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); }
Example #22
Source File: StreamsTester.java From football-events with MIT License | 5 votes |
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); }
Example #23
Source File: HadoopFileSystem.java From jsr203-hadoop with Apache License 2.0 | 5 votes |
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); }*/ }
Example #24
Source File: IoUtilTest.java From agrona with Apache License 2.0 | 5 votes |
@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)); }
Example #25
Source File: IoUtilTest.java From agrona with Apache License 2.0 | 5 votes |
@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())); }
Example #26
Source File: SFTPFileSystemTest.java From sftp-fs with Apache License 2.0 | 5 votes |
@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"))); }
Example #27
Source File: SFTPFileSystemTest.java From sftp-fs with Apache License 2.0 | 5 votes |
@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"))); }
Example #28
Source File: SFTPFileSystem.java From sftp-fs with Apache License 2.0 | 5 votes |
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()); } }
Example #29
Source File: MCRFileSystemProvider.java From mycore with GNU General Public License v3.0 | 5 votes |
@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); } }
Example #30
Source File: ResponseTransformer.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * 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(); } }; }