Example usage for java.nio.file Path getFileName

List of usage examples for java.nio.file Path getFileName

Introduction

In this page you can find the example usage for java.nio.file Path getFileName.

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by this path as a Path object.

Usage

From source file:business.services.FileService.java

public File clone(File file) {
    try {//from w  w w.  j  a va 2  s  . c o m
        FileSystem fileSystem = FileSystems.getDefault();
        // source
        Path source = fileSystem.getPath(uploadPath, file.getFilename());
        // target
        Path path = fileSystem.getPath(uploadPath).normalize();
        String prefix = getBasename(file.getFilename());
        String suffix = getExtension(file.getFilename());
        Path target = Files.createTempFile(path, prefix, suffix).normalize();
        // copy
        log.info("Copying " + source + " to " + target + " ...");
        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
        // save clone
        File result = file.clone();
        result.setFilename(target.getFileName().toString());
        return save(result);
    } catch (IOException e) {
        log.error(e);
        throw new FileCopyError();
    }
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

@Override
public void copy(UrlTreeMetaData<InputStream> metadata, String dstDir, UrlTreeContext ctx)
        throws BadContentException {

    String srcPathName = metadata.getAbsolutePath();
    Path srcPath = this.generateFileObj(srcPathName);
    Path dstPath = this.generateFileObj(dstDir);

    logger.debug("copy: " + srcPath.toAbsolutePath() + " to " + dstPath.toAbsolutePath());

    try {//from w  w w .  j a v a 2s  .  co  m
        Files.copy(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.COPY_ATTRIBUTES,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException("cannot copy file", e);
    }
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

@Override
public void move(UrlTreeMetaData<InputStream> metadata, String dstDir, UrlTreeContext ctx)
        throws BadContentException {

    String srcPathName = metadata.getAbsolutePath();
    Path srcPath = this.generateFileObj(srcPathName);
    Path dstPath = this.generateFileObj(dstDir);

    logger.debug("move: " + srcPath.toAbsolutePath() + " to " + dstPath.toAbsolutePath());

    try {/*w w  w . j a v  a2 s  .  c  o  m*/
        Files.move(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.ATOMIC_MOVE,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException("cannot copy file", e);
    }
}

From source file:com.facebook.buck.io.ProjectFilesystemTest.java

@Test
public void testWalkFileTreeWhenProjectRootIsWorkingDir() throws IOException {
    ProjectFilesystem projectFilesystem = new ProjectFilesystem(Paths.get(".").toAbsolutePath());
    final ImmutableList.Builder<String> fileNames = ImmutableList.builder();

    Path pathRelativeToProjectRoot = Paths
            .get("test/com/facebook/buck/io/testdata/directory_traversal_ignore_paths");
    projectFilesystem.walkRelativeFileTree(pathRelativeToProjectRoot, new SimpleFileVisitor<Path>() {
        @Override/*from w  ww. j a  v a 2 s.co m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            fileNames.add(file.getFileName().toString());
            return FileVisitResult.CONTINUE;
        }
    });

    assertThat(fileNames.build(), containsInAnyOrder("file", "a_file", "b_file", "b_c_file", "b_d_file"));
}

From source file:com.facebook.buck.io.ProjectFilesystemTest.java

@Test
public void testWalkFileTreeWhenProjectRootIsNotWorkingDir() throws IOException {
    tmp.newFolder("dir");
    tmp.newFile("dir/file.txt");
    tmp.newFolder("dir/dir2");
    tmp.newFile("dir/dir2/file2.txt");

    final ImmutableList.Builder<String> fileNames = ImmutableList.builder();

    filesystem.walkRelativeFileTree(Paths.get("dir"), new SimpleFileVisitor<Path>() {
        @Override/*from  w ww  . j ava2  s  .c  o m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            fileNames.add(file.getFileName().toString());
            return FileVisitResult.CONTINUE;
        }
    });

    assertThat(fileNames.build(), containsInAnyOrder("file.txt", "file2.txt"));
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Execute the given query/*from w  w  w .j a  v a2 s. co  m*/
 * @param clientId the client id
 * @param async whether to execute synchronously or asynchronously
 * @param params the query parameters
 * @return the result file
 */
@RequestMapping(value = "/execute/{clientId}", method = RequestMethod.GET)
@ResponseBody
public RepoFile executeQuery(@PathVariable("clientId") String clientId,
        @RequestParam(value = "async", defaultValue = "true") boolean async,
        @RequestParam("params") String params) throws IOException {
    String url = aisViewUrl + params;

    // Create the client ID folder
    Path dir = repoRoot.resolve(clientId);
    if (!Files.exists(dir)) {
        Files.createDirectories(dir);
    }

    // Create a new file to hold the result
    // (could have used Files.createTempFile, but this should be enough to create a unique file)
    Date now = new Date();
    Path file = Files.createTempFile(dir, new SimpleDateFormat("MM-dd HHmmss ").format(now),
            fileType(url) + DOWNLOAD_SUFFIX);
    String fileName = file.getFileName().toString();

    // Load the file
    Future<Path> result = asyncLoadFile(url, file);
    if (!async) {
        try {
            Path path = result.get();
            // The resulting path may actually by an error file
            fileName = path.getFileName().toString();
        } catch (Exception e) {
            log.severe("Error executing query: " + params + ", error: " + e);
        }
    }

    // Return a RepoFile for the newly created file
    RepoFile vo = new RepoFile();
    vo.setName(fileName);
    vo.setPath(clientId + "/" + fileName);
    vo.setUpdated(now);
    vo.setSize(0L);
    return vo;
}

From source file:org.alfresco.repo.bulkimport.impl.DirectoryAnalyserImpl.java

private Path getParentOfMetadatafile(Path metadataFile) {
    Path result = null;/*from  w  ww .ja v a  2  s  .  c  o m*/

    if (!isMetadataFile(metadataFile)) {
        throw new IllegalStateException(FileUtils.getFileName(metadataFile) + " is not a metadata file.");
    }

    String name = metadataFile.getFileName().toString();
    String contentName = name.substring(0, name.length()
            - (MetadataLoader.METADATA_SUFFIX + metadataLoader.getMetadataFileExtension()).length());

    result = metadataFile.getParent().resolve(contentName);

    return (result);
}

From source file:com.bc.fiduceo.post.PostProcessingTool.java

private void computeFile(Path mmdFile, final SourceTargetManager manager, List<PostProcessing> processings)
        throws IOException, InvalidRangeException {
    final long startTime = context.getStartDate().getTime();
    final long endTime = context.getEndDate().getTime();
    if (isFileInTimeRange(startTime, endTime, mmdFile.getFileName().toString())) {
        logger.info("Compute file '" + mmdFile.getFileName().toString() + "'");
        final Path source = manager.getSource(mmdFile);
        final Path target = manager.getTargetPath(mmdFile);

        NetcdfFile reader = null;//  w w w .  jav a  2  s .co  m
        NetcdfFileWriter writer = null;

        try {
            final String absSource = source.toAbsolutePath().toString();

            // open the file that way is needed because the standard open mechanism changes the file size
            reader = NetCDFUtils.openReadOnly(absSource);

            final String absTarget = target.toAbsolutePath().toString();
            if (DataFormatType.NETCDF.name().equalsIgnoreCase(reader.getFileTypeId())) {
                writer = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf3, absTarget);
            } else {
                final Nc4Chunking chunking = Nc4ChunkingDefault.factory(Nc4Chunking.Strategy.standard, 5, true);
                writer = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf4, absTarget, chunking);
            }

            run(reader, writer, processings);
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                // when writer is in define mode, the file has not been created. Closing it in this state causes a
                // null pointer exception tb 2016-12-21
                if (!writer.isDefineMode()) {
                    writer.close();
                }
            }
        }
    }
}

From source file:org.alfresco.repo.bulkimport.impl.DirectoryAnalyserImpl.java

private Path getParentOfVersionFile(Path versionFile) {
    Path result = null;//w  ww  .  jav a  2  s.c  om

    if (!isVersionFile(versionFile)) {
        throw new IllegalStateException(FileUtils.getFileName(versionFile) + " is not a version file.");
    }

    String parentFilename = versionFile.getFileName().toString().replaceFirst(VERSION_SUFFIX_REGEX, "");

    result = versionFile.getParent().resolve(parentFilename);

    return (result);
}

From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java

private static Path pack(final Path folder, JsonObject graph, String tkName)
        throws IOException, URISyntaxException {
    String namespace = splAppNamespace(graph);
    String name = splAppName(graph);

    Path zipFilePath = Paths.get(folder.toAbsolutePath().toString() + ".zip");
    String workingDir = zipFilePath.getParent().toString();

    Path topologyToolkit = TkInfo.getTopologyToolkitRoot().getAbsoluteFile().toPath();

    // Paths to copy into the toolkit
    Map<Path, String> paths = new HashMap<>();

    // tkManifest is the list of toolkits contained in the archive
    try (PrintWriter tkManifest = new PrintWriter("manifest_tk.txt", "UTF-8")) {
        tkManifest.println(tkName);//from   w  w  w.j a v  a 2  s .c om
        tkManifest.println("com.ibm.streamsx.topology");

        JsonObject configSpl = object(graph, CONFIG, "spl");
        if (configSpl != null) {
            objectArray(configSpl, "toolkits", tk -> {
                File tkRoot = new File(jstring(tk, "root"));
                String tkRootName = tkRoot.getName();
                tkManifest.println(tkRootName);
                paths.put(tkRoot.toPath(), tkRootName);
            });
        }
    }

    // mainComposite is a string of the namespace and the main composite.
    // This is used by the Makefile
    try (PrintWriter mainComposite = new PrintWriter("main_composite.txt", "UTF-8")) {
        mainComposite.print(namespace + "::" + name);
    }

    Path manifest = Paths.get(workingDir, "manifest_tk.txt");
    Path mainComp = Paths.get(workingDir, "main_composite.txt");
    Path makefile = topologyToolkit
            .resolve(Paths.get("opt", "python", "templates", "common", "Makefile.template"));

    paths.put(topologyToolkit, topologyToolkit.getFileName().toString());
    paths.put(manifest, "manifest_tk.txt");
    paths.put(mainComp, "main_composite.txt");
    paths.put(makefile, "Makefile");
    paths.put(folder, folder.getFileName().toString());

    addAllToZippedArchive(paths, zipFilePath);
    manifest.toFile().delete();
    mainComp.toFile().delete();

    return zipFilePath;
}