Example usage for java.nio.file Files isSameFile

List of usage examples for java.nio.file Files isSameFile

Introduction

In this page you can find the example usage for java.nio.file Files isSameFile.

Prototype

public static boolean isSameFile(Path path, Path path2) throws IOException 

Source Link

Document

Tests if two paths locate the same file.

Usage

From source file:Main.java

public static void main(String[] args) {

    Path path01 = Paths.get("/tutorial/Java/JavaFX/Topic.txt");
    Path path02 = Paths.get("C:/tutorial/Java/JavaFX/Topic.txt");

    // compare using Files.isSameFile
    try {/*from ww w.j  a va 2  s . c o m*/
        boolean check = Files.isSameFile(path01, path02);
        if (check) {
            System.out.println("The paths locate the same file!");
        } else {
            System.out.println("The paths does not locate the same file!");
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:Main.java

public static void main(String[] args) {
    // Assume that C:\Java_Dev\test1.txt file exists
    Path p1 = Paths.get("C:\\Java_Dev\\test1.txt");
    Path p2 = Paths.get("C:\\Java_Dev\\..\\Java_Dev\\test1.txt");

    // Assume that C:\abc.txt file does not exist
    Path p3 = Paths.get("C:\\abc.txt");
    Path p4 = Paths.get("C:\\abc.txt");

    try {//  ww  w  .j  av  a 2s . co  m
        boolean isSame = Files.isSameFile(p1, p2);
        System.out.println("p1 and  p2  are   the   same:  " + isSame);

        isSame = Files.isSameFile(p3, p4);
        System.out.println("p3 and  p4  are   the   same:  " + isSame);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

private static void testSameFile(Path path1, Path path2) {
    try {/*from  www . ja  v a  2  s . c om*/
        if (Files.isSameFile(path1, path2)) {
            System.out.println("same file");
        } else {
            System.out.println("NOT the same file");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.ballerinalang.langserver.command.executors.CreateTestExecutor.java

/**
 * Returns a pair of current module path and calculated target test path.
 *
 * @param sourceFilePath source file path
 * @param projectRoot    project root//from   w  w  w  . j av  a2 s  . c  om
 * @return a pair of currentModule path(left-side) and target test path(right-side)
 */
private static ImmutablePair<Path, Path> getTestsDirPath(Path sourceFilePath, Path projectRoot) {
    if (sourceFilePath == null || projectRoot == null) {
        return null;
    }
    Path currentModulePath = projectRoot;
    Path prevSourceRoot = sourceFilePath.getParent();
    List<String> pathParts = new ArrayList<>();
    try {
        while (prevSourceRoot != null) {
            Path newSourceRoot = prevSourceRoot.getParent();
            currentModulePath = prevSourceRoot;
            if (newSourceRoot == null || Files.isSameFile(newSourceRoot, projectRoot)) {
                // We have reached the project root
                break;
            }
            pathParts.add(prevSourceRoot.getFileName().toString());
            prevSourceRoot = newSourceRoot;
        }
    } catch (IOException e) {
        // do nothing
    }

    // Append `tests` path
    Path testDirPath = currentModulePath.resolve(ProjectDirConstants.TEST_DIR_NAME);

    // Add same directory structure inside the module
    for (String part : pathParts) {
        testDirPath = testDirPath.resolve(part);
    }

    return new ImmutablePair<>(currentModulePath, testDirPath);
}

From source file:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public Set<File> getHistory() throws IOException {
    Path history = getHistoryPath();
    if (Files.exists(history)) {

        Path currentConfigArchive = getConfigurationPath(getCurrentConfigurationName());
        Predicate<Path> currentConfig = p -> {
            try {
                return Files.isSameFile(p, currentConfigArchive);
            } catch (IOException e) {
                return false;
            }/* w w  w  .  j  a  va  2  s.c  o  m*/
        };

        return Files.list(history).filter(currentConfig.negate()).map(Path::toFile).collect(Collectors.toSet());
    }

    return new LinkedHashSet<>();
}

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {/*from   w  w w.  j a va 2 s  . com*/
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:org.cloudfoundry.util.FileUtils.java

private static void write(Path root, Path path, ZipArchiveOutputStream out) {
    try {//from   w w  w.j av  a 2  s.  c o m
        if (Files.isSameFile(root, path)) {
            return;
        }

        ZipArchiveEntry entry = new ZipArchiveEntry(getRelativePathName(root, path));
        entry.setUnixMode(getUnixMode(path));
        entry.setLastModifiedTime(Files.getLastModifiedTime(path));
        out.putArchiveEntry(entry);

        if (Files.isRegularFile(path)) {
            Files.copy(path, out);
        }

        out.closeArchiveEntry();
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceCopyWebdavDirectoryTestExecutionListener.java

private void cleanDirectory(Path directory) {
    if (!Files.isDirectory(directory)) {
        return;//from  w w  w  .  j av a 2  s  . c  om
    }

    try {
        log.debug("Remove all Contents of Directory {}", directory.toAbsolutePath().toString());
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (!Files.isSameFile(dir, directory)) {
                    Files.delete(dir);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        Files.delete(directory);
    } catch (IOException e) {
        throw new RuntimeException(
                String.format("IOException while cleaning Directory %s", directory.toAbsolutePath().toString()),
                e);
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceChecksumServiceImpl.java

private static boolean isSamePath(Path source, Path destination) {
    try {/* w ww . j  a v  a  2 s .  c  om*/
        return Files.isSameFile(source, destination);
    } catch (IOException e) {
        val logMessage = String.format("Cannot determine the Equality of the Directories %s and %s", source,
                destination);
        log.error(logMessage, e);
        throw new OwncloudLocalResourceChecksumServiceException(logMessage, e);
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceChecksumServiceTest.java

private boolean isSameFile(Path source, Path destination) {
    try {/*  w  w w  .  j  a  v a2  s.c  om*/
        return Files.isSameFile(source, destination);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}