List of usage examples for java.nio.file Files isSameFile
public static boolean isSameFile(Path path, Path path2) throws IOException
From source file:org.xmlsh.sh.shell.Shell.java
private static String tryFindHome() { getLogger().entry();/*from ww w. j ava 2 s.c om*/ try { CodeSource cs = Shell.class.getProtectionDomain().getCodeSource(); if (cs != null) { Path p = Paths.get(cs.getLocation().toURI()); String sdir = null; while ((p = FileUtils.resolveLink(p)) != null) { while (p != null && !Files.isDirectory(p)) p = FileUtils.getParent(p); if (p == null) break; if (sdir == null) sdir = p.toString(); // first dir found Path parent = FileUtils.getParent(p); if (parent == null || parent == p || Files.isSameFile(parent, p)) break; p = parent; if (p != null) { if (Files.isDirectory(p.resolve("modules")) || Files.isDirectory(p.resolve("lib"))) return getLogger().exit(p.toString()); } } return getLogger().exit(sdir); } } catch (SecurityException | URISyntaxException | IOException e) { getLogger().catching(e); } return null; }
From source file:org.apache.solr.cloud.api.collections.CollectionsAPIDistributedZkTest.java
private void checkInstanceDirs(JettySolrRunner jetty) throws IOException { CoreContainer cores = jetty.getCoreContainer(); Collection<SolrCore> theCores = cores.getCores(); for (SolrCore core : theCores) { // look for core props file Path instancedir = (Path) core.getResourceLoader().getInstancePath(); assertTrue("Could not find expected core.properties file", Files.exists(instancedir.resolve("core.properties"))); Path expected = Paths.get(jetty.getSolrHome()).toAbsolutePath().resolve(core.getName()); assertTrue("Expected: " + expected + "\nFrom core stats: " + instancedir, Files.isSameFile(expected, instancedir)); }//from w w w. j a v a 2s .c om }
From source file:org.tinymediamanager.core.Utils.java
/** * modified version of commons-io FileUtils.moveDirectory(); adapted to Java 7 NIO<br> * since renameTo() might not work in first place, retry it up to 5 times.<br> * (better wait 5 sec for success, than always copying a 50gig directory ;)<br> * <b>And NO, we're NOT doing a copy+delete as fallback!</b> * //from www .j a va 2 s. co m * @param srcDir * the directory to be moved * @param destDir * the destination directory * @return true, if successful * @throws IOException * if an IO error occurs moving the file */ public static boolean moveDirectorySafe(Path srcDir, Path destDir) throws IOException { // rip-off from // http://svn.apache.org/repos/asf/commons/proper/io/trunk/src/main/java/org/apache/commons/io/FileUtils.java if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.toAbsolutePath().toString().equals(destDir.toAbsolutePath().toString())) { LOGGER.debug("try to move folder " + srcDir + " to " + destDir); if (!Files.isDirectory(srcDir)) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist, or is not a directory"); } if (Files.exists(destDir) && !Files.isSameFile(destDir, srcDir)) { // extra check for Windows/OSX, where the File.equals is case insensitive // so we know now, that the Dir is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destDir + "' already exists"); } if (!Files.exists(destDir.getParent())) { // create parent folder structure, else renameTo does not work try { Files.createDirectories(destDir.getParent()); } catch (Exception e) { LOGGER.error("could not create directory structure " + destDir.getParent()); // but we try a move anyway... } } // rename folder; try 5 times and wait a sec boolean rename = false; for (int i = 0; i < 5; i++) { try { // need atomic fs move for changing cASE Files.move(srcDir, destDir, StandardCopyOption.ATOMIC_MOVE); rename = true;// no exception } catch (AtomicMoveNotSupportedException a) { // if it fails (b/c not on same file system) use that try { Files.move(srcDir, destDir, StandardCopyOption.REPLACE_EXISTING); rename = true; // no exception } catch (IOException e) { } } catch (IOException e) { } if (rename) { break; // ok it worked, step out } try { LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } // ok, we tried it 5 times - it still seems to be locked somehow. Continue // with copying as fallback // NOOO - we don't like to have some files copied and some not. if (!rename) { LOGGER.error("Failed to rename directory '" + srcDir + " to " + destDir); LOGGER.error("Movie renaming aborted."); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcDir, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved folder " + srcDir + " to " + destDir); return true; } } return true; // dir are equal }
From source file:com.android.repository.util.InstallerUtilTest.java
public void testUnzip() throws Exception { if (new MockFileOp().isWindows()) { // can't run on windows. return;//from www . j a v a 2s .com } // zip needs a real file, so no MockFileOp for us. FileOp fop = FileOpUtils.create(); Path root = Files.createTempDirectory("InstallerUtilTest"); Path outRoot = Files.createTempDirectory("InstallerUtilTest"); try { Path file1 = root.resolve("foo"); Files.write(file1, "content".getBytes()); Path dir1 = root.resolve("bar"); Files.createDirectories(dir1); Path file2 = dir1.resolve("baz"); Files.write(file2, "content2".getBytes()); Files.createSymbolicLink(root.resolve("link1"), dir1); Files.createSymbolicLink(root.resolve("link2"), file2); Path outZip = outRoot.resolve("out.zip"); try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(outZip.toFile()); Stream<Path> listing = Files.walk(root)) { listing.forEach(path -> { try { ZipArchiveEntry archiveEntry = (ZipArchiveEntry) out.createArchiveEntry(path.toFile(), root.relativize(path).toString()); out.putArchiveEntry(archiveEntry); if (Files.isSymbolicLink(path)) { archiveEntry.setUnixMode(UnixStat.LINK_FLAG | archiveEntry.getUnixMode()); out.write(path.getParent().relativize(Files.readSymbolicLink(path)).toString() .getBytes()); } else if (!Files.isDirectory(path)) { out.write(Files.readAllBytes(path)); } out.closeArchiveEntry(); } catch (Exception e) { fail(); } }); } Path unzipped = outRoot.resolve("unzipped"); Files.createDirectories(unzipped); InstallerUtil.unzip(outZip.toFile(), unzipped.toFile(), fop, 1, new FakeProgressIndicator()); assertEquals("content", new String(Files.readAllBytes(unzipped.resolve("foo")))); Path resultDir = unzipped.resolve("bar"); Path resultFile2 = resultDir.resolve("baz"); assertEquals("content2", new String(Files.readAllBytes(resultFile2))); Path resultLink = unzipped.resolve("link1"); assertTrue(Files.isDirectory(resultLink)); assertTrue(Files.isSymbolicLink(resultLink)); assertTrue(Files.isSameFile(resultLink, resultDir)); Path resultLink2 = unzipped.resolve("link2"); assertEquals("content2", new String(Files.readAllBytes(resultLink2))); assertTrue(Files.isSymbolicLink(resultLink2)); assertTrue(Files.isSameFile(resultLink2, resultFile2)); } finally { fop.deleteFileOrFolder(root.toFile()); fop.deleteFileOrFolder(outRoot.toFile()); } }
From source file:org.tinymediamanager.core.Utils.java
/** * modified version of commons-io FileUtils.moveFile(); adapted to Java 7 NIO<br> * since renameTo() might not work in first place, retry it up to 5 times.<br> * (better wait 5 sec for success, than always copying a 50gig directory ;)<br> * <b>And NO, we're NOT doing a copy+delete as fallback!</b> * /*from w w w. jav a2s . co m*/ * @param srcFile * the file to be moved * @param destFile * the destination file * @throws NullPointerException * if source or destination is {@code null} * @throws FileExistsException * if the destination file exists * @throws IOException * if source or destination is invalid * @throws IOException * if an IO error occurs moving the file */ public static boolean moveFileSafe(final Path srcFile, final Path destFile) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } // if (!srcFile.equals(destFile)) { if (!srcFile.toAbsolutePath().toString().equals(destFile.toAbsolutePath().toString())) { LOGGER.debug("try to move file " + srcFile + " to " + destFile); if (!Files.exists(srcFile)) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (Files.isDirectory(srcFile)) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (Files.exists(destFile) && !Files.isSameFile(destFile, srcFile)) { // extra check for windows, where the File.equals is case insensitive // so we know now, that the File is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destFile + "' already exists"); } if (Files.isDirectory(destFile)) { throw new IOException("Destination '" + destFile + "' is a directory"); } // rename folder; try 5 times and wait a sec boolean rename = false; for (int i = 0; i < 5; i++) { try { // need atomic fs move for changing cASE Files.move(srcFile, destFile, StandardCopyOption.ATOMIC_MOVE); rename = true;// no exception } catch (AtomicMoveNotSupportedException a) { // if it fails (b/c not on same file system) use that try { Files.move(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING); rename = true; // no exception } catch (IOException e) { LOGGER.warn("rename problem: " + e.getMessage()); } } catch (IOException e) { LOGGER.warn("rename problem: " + e.getMessage()); } if (rename) { break; // ok it worked, step out } try { LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } if (!rename) { LOGGER.error("Failed to rename file '" + srcFile + " to " + destFile); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcFile, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved file from " + srcFile + " to " + destFile); return true; } } return true; // files are equal }
From source file:de.fosd.jdime.artifact.file.FileArtifact.java
/** * Copies the {@link #original} to the {@link #file} of this {@link FileArtifact}. * * @throws IOException/* ww w . j a v a 2s. c o m*/ * see {@link FileUtils#copyFile(File, File)} */ private void copyFile() throws IOException { if (!Files.isSameFile(original.toPath(), file.toPath())) { FileUtils.copyFile(original, file); } }
From source file:org.schedulesdirect.grabber.Grabber.java
private void removeExpiredSchedules(FileSystem vfs) throws IOException, JSONException { final int[] i = new int[] { 0 }; final Path root = vfs.getPath("schedules"); Files.walkFileTree(root, new FileVisitor<Path>() { @Override/* w ww. j a v a 2 s. c o m*/ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return !Files.isSameFile(dir, root) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try (InputStream ins = Files.newInputStream(file)) { JSONArray sched = Config.get().getObjectMapper() .readValue(IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class) .getJSONArray("programs"); if (isScheduleExpired(sched)) { Files.delete(file); ++i[0]; } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); LOG.info(String.format("Removed %d expired schedule(s).", i[0])); }
From source file:org.tinymediamanager.core.Utils.java
/** * copy a file, preserving the attributes * * @param srcFile/* www . j ava2s.co m*/ * the file to be copied * @param destFile * the target * @param overwrite * overwrite the target? * @return true/false * @throws NullPointerException * if source or destination is {@code null} * @throws FileExistsException * if the destination file exists * @throws IOException * if source or destination is invalid * @throws IOException * if an IO error occurs moving the file */ public static boolean copyFileSafe(final Path srcFile, final Path destFile, boolean overwrite) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } // if (!srcFile.equals(destFile)) { if (!srcFile.toAbsolutePath().toString().equals(destFile.toAbsolutePath().toString())) { LOGGER.debug("try to copy file " + srcFile + " to " + destFile); if (!Files.exists(srcFile)) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (Files.isDirectory(srcFile)) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (!overwrite) { if (Files.exists(destFile) && !Files.isSameFile(destFile, srcFile)) { // extra check for windows, where the File.equals is case insensitive // so we know now, that the File is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destFile + "' already exists"); } } if (Files.isDirectory(destFile)) { throw new IOException("Destination '" + destFile + "' is a directory"); } // rename folder; try 5 times and wait a sec boolean rename = false; for (int i = 0; i < 5; i++) { try { // replace existing for changing cASE Files.copy(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); rename = true;// no exception } catch (IOException e) { } if (rename) { break; // ok it worked, step out } try { LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } if (!rename) { LOGGER.error("Failed to rename file '" + srcFile + " to " + destFile); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcFile, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved file from " + srcFile + " to " + destFile); return true; } } return true; // files are equal }
From source file:org.schedulesdirect.grabber.Grabber.java
private void removeUnusedPrograms(FileSystem vfs) throws IOException { final int[] i = new int[] { 0 }; final Path root = vfs.getPath("programs"); Files.walkFileTree(root, new FileVisitor<Path>() { @Override/* ww w. j a va 2 s . c om*/ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String id = file.getName(file.getNameCount() - 1).toString(); id = id.substring(0, id.indexOf('.')); if (!activeProgIds.contains(id)) { if (LOG.isDebugEnabled()) LOG.debug(String.format("CacheCleaner: Unused '%s'", id)); Files.delete(file); ++i[0]; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); LOG.info(String.format("Removed %d unused program(s).", i[0])); }
From source file:org.schedulesdirect.grabber.Grabber.java
private void removeIgnoredStations(FileSystem vfs) throws IOException { final int[] i = new int[] { 0 }; final Path root = vfs.getPath("schedules"); Files.walkFileTree(root, new FileVisitor<Path>() { @Override//w w w. j a v a2 s . com public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String id = file.getName(file.getNameCount() - 1).toString(); id = id.substring(0, id.indexOf('.')); if (stationList != null && !stationList.contains(id)) { if (LOG.isDebugEnabled()) LOG.debug(String.format("CacheCleaner: Remove '%s'", id)); Files.delete(file); ++i[0]; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); LOG.info(String.format("Removed %d ignored station(s).", i[0])); }