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:com.fizzed.blaze.util.Streamables.java

static public StreamableOutput output(Path path) {
    Objects.requireNonNull(path, "path cannot be null");
    return new StreamableOutput(new DeferredFileOutputStream(path), path.getFileName().toString(), path, null);
}

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * Resizes the image and writes it to the disk.
 *
 * @param sourceImage original image file.
 * @param width requested width//  w  w w. ja va 2s . c om
 * @param height requested height
 * @param quality requested destination file quality
 * @param destFile file to write to
 * @throws IOException when IO Exception occurs.
 */
private static void resizeImage(BufferedImage sourceImage, int width, int height, float quality, Path destFile)
        throws IOException {
    String format = FileUtils.getExtension(destFile.getFileName().toString());
    format = format != null ? format.toLowerCase() : null;
    try (OutputStream out = Files.newOutputStream(destFile)) {
        try {
            Thumbnails.of(sourceImage).size(width, height).keepAspectRatio(false).outputQuality(quality)
                    .outputFormat(format).toOutputStream(out);
            // for some special files outputQuality couses error:
            //IllegalStateException inner Thumbnailator jar. When exception is thrown
            // image is resized without quality
            // When http://code.google.com/p/thumbnailator/issues/detail?id=9
            // will be fixed this try catch can be deleted. Only:
            //Thumbnails.of(sourceImage).size(width, height).keepAspectRatio(false)
            //  .outputQuality(quality).toOutputStream(out);
            // should remain.
        } catch (IllegalStateException e) {
            Thumbnails.of(sourceImage).size(width, height).keepAspectRatio(false).outputFormat(format)
                    .toOutputStream(out);
        }
    }
}

From source file:com.buaa.cfs.utils.IOUtils.java

/**
 * Return the complete list of files in a directory as strings.<p/>
 * <p>//from   ww w .j a v  a 2s. c  o m
 * This is better than File#listDir because it does not ignore IOExceptions.
 *
 * @param dir    The directory to list.
 * @param filter If non-null, the filter to use when listing this directory.
 *
 * @return The list of files in the directory.
 *
 * @throws IOException On I/O error
 */
public static List<String> listDirectory(File dir, FilenameFilter filter) throws IOException {
    ArrayList<String> list = new ArrayList<String>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir.toPath())) {
        for (Path entry : stream) {
            String fileName = entry.getFileName().toString();
            if ((filter == null) || filter.accept(dir, fileName)) {
                list.add(fileName);
            }
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
    return list;
}

From source file:com.swingtech.apps.filemgmt.util.MimeTypeUtils.java

public static String probeContentType(Path file) throws IOException {
    String mimetype = Files.probeContentType(file);
    if (mimetype != null)
        return mimetype;

    mimetype = tika.detect(file.toFile());
    if (mimetype != null)
        return mimetype;

    return getMimeType(FilenameUtils.getExtension(String.valueOf(file.getFileName())));
}

From source file:Main.java

public static void printDetails(Path p) {
    System.out.println("Details for path: " + p);

    int count = p.getNameCount();
    System.out.println("Name count: " + count);

    for (int i = 0; i < count; i++) {
        Path name = p.getName(i);
        System.out.println("Name at  index   " + i + "  is " + name);
    }/*from w  ww  . ja v  a2 s  .  c om*/

    Path parent = p.getParent();
    Path root = p.getRoot();
    Path fileName = p.getFileName();
    System.out.println("Parent: " + parent + ", Root:   " + root + ", File Name: " + fileName);
    System.out.println("Absolute Path: " + p.isAbsolute());
}

From source file:org.bonitasoft.web.designer.controller.utils.HttpFile.java

public static void writeFileInResponse(HttpServletRequest request, HttpServletResponse response, Path filePath)
        throws IOException {
    if (!isExistingFilePath(response, filePath)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;// w  w  w  .  j av a2 s.com
    }
    writeFileInResponse(response, filePath,
            request.getServletContext().getMimeType(filePath.getFileName().toString()), "inline");
}

From source file:ch.bender.evacuate.Helper.java

/**
 * Deletes a whole directory (recursively)
 * <p>/*from   w ww.  j  av  a2s .c om*/
 * @param aDir
 *        a folder to be deleted (must not be null)
 * @throws IOException
 */
public static void deleteDirRecursive(Path aDir) throws IOException {
    if (aDir == null) {
        throw new IllegalArgumentException("aDir must not be null");
    }

    if (Files.notExists(aDir)) {
        return;
    }

    if (!Files.isDirectory(aDir)) {
        throw new IllegalArgumentException("given aDir is not a directory");
    }

    Files.walkFileTree(aDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        /**
         * @see java.nio.file.SimpleFileVisitor#preVisitDirectory(java.lang.Object, java.nio.file.attribute.BasicFileAttributes)
         */
        @Override
        public FileVisitResult preVisitDirectory(Path aFile, BasicFileAttributes aAttrs) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return FileVisitResult.CONTINUE;
        }

        @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 (dir.isAbsolute() && dir.getRoot().equals(dir)) {
                myLog.debug("root cannot be deleted: " + dir.toString());
                return FileVisitResult.CONTINUE;
            }

            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:com.github.anba.test262.environment.Environments.java

/**
 * Creates a new Rhino environment/*  w  w w .j  a v  a 2  s. c  o  m*/
 */
public static <T extends GlobalObject> EnvironmentProvider<T> rhino(final Configuration configuration) {
    final int version = configuration.getInt("rhino.version", Context.VERSION_DEFAULT);
    final String compiler = configuration.getString("rhino.compiler.default");
    List<?> enabledFeatures = configuration.getList("rhino.features.enabled", emptyList());
    List<?> disabledFeatures = configuration.getList("rhino.features.disabled", emptyList());
    final Set<Integer> enabled = intoCollection(filterMap(enabledFeatures, notEmptyString, toInteger),
            new HashSet<Integer>());
    final Set<Integer> disabled = intoCollection(filterMap(disabledFeatures, notEmptyString, toInteger),
            new HashSet<Integer>());

    /**
     * Initializes the global {@link ContextFactory} according to the
     * supplied configuration
     * 
     * @see ContextFactory#initGlobal(ContextFactory)
     */
    final ContextFactory factory = new ContextFactory() {
        @Override
        protected boolean hasFeature(Context cx, int featureIndex) {
            if (enabled.contains(featureIndex)) {
                return true;
            } else if (disabled.contains(featureIndex)) {
                return false;
            }
            return super.hasFeature(cx, featureIndex);
        }

        @Override
        protected Context makeContext() {
            Context context = super.makeContext();
            context.setLanguageVersion(version);
            return context;
        }
    };

    EnvironmentProvider<RhinoGlobalObject> provider = new EnvironmentProvider<RhinoGlobalObject>() {
        @Override
        public RhinoEnv<RhinoGlobalObject> environment(final String testsuite, final String sourceName,
                final Test262Info info) {
            Configuration c = configuration.subset(testsuite);
            final boolean strictSupported = c.getBoolean("strict", false);
            final String encoding = c.getString("encoding", "UTF-8");
            final String libpath = c.getString("lib_path");

            final Context cx = factory.enterContext();
            final AtomicReference<RhinoGlobalObject> $global = new AtomicReference<>();

            final RhinoEnv<RhinoGlobalObject> environment = new RhinoEnv<RhinoGlobalObject>() {
                @Override
                public RhinoGlobalObject global() {
                    return $global.get();
                }

                @Override
                protected String getEvaluator() {
                    return compiler;
                }

                @Override
                protected String getCharsetName() {
                    return encoding;
                }

                @Override
                public void exit() {
                    Context.exit();
                }
            };

            @SuppressWarnings({ "serial" })
            final RhinoGlobalObject global = new RhinoGlobalObject() {
                {
                    cx.initStandardObjects(this, false);
                }

                @Override
                protected boolean isStrictSupported() {
                    return strictSupported;
                }

                @Override
                protected String getDescription() {
                    return info.getDescription();
                }

                @Override
                protected void failure(String message) {
                    failWith(message, sourceName);
                }

                @Override
                protected void include(Path path) throws IOException {
                    // resolve the input file against the library path
                    Path file = Paths.get(libpath).resolve(path);
                    InputStream source = Files.newInputStream(file);
                    environment.eval(file.getFileName().toString(), source);
                }
            };

            $global.set(global);

            return environment;
        }
    };

    @SuppressWarnings("unchecked")
    EnvironmentProvider<T> p = (EnvironmentProvider<T>) provider;

    return p;
}

From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java

/**
 * Instantiates an attachment mail part from a file
 * @param file the attachment file/*  w  w  w  .j  a v a 2 s. c  o  m*/
 * @param name the name of the attachment.
 */
public static AttachmentMailPart fromFile(String file, String name) throws MessagingException {
    // Check that the file is valid
    Path path = Paths.get(file);
    if (!Files.isRegularFile(path)) {
        throw new MessagingException("Invalid file attachment: " + file);
    }

    // If name is not specified, compute it from the file
    if (StringUtils.isBlank(name)) {
        name = path.getFileName().toString();
    }

    // Instantiate a mail attachment
    AttachmentMailPart a = new AttachmentMailPart(name);
    a.file = file;
    return a;
}

From source file:io.redlink.solrlib.SolrCoreDescriptor.java

static void unpackSolrCoreZip(Path solrCoreBundle, Path solrHome, ClassLoader classLoader) throws IOException {
    final String contentType = Files.probeContentType(solrCoreBundle);
    if ("application/zip".equals(contentType) ||
    //fallback if Files.probeContentType(..) fails (such as on Max OS X)
            (contentType == null/*  w w w  .  j av a 2s.  c om*/
                    && StringUtils.endsWithAny(solrCoreBundle.getFileName().toString(), ".zip", ".jar"))) {
        LoggerFactory.getLogger(SolrCoreDescriptor.class).debug("Unpacking SolrCore zip {} to {}",
                solrCoreBundle, solrHome);
        try (FileSystem fs = FileSystems.newFileSystem(solrCoreBundle, classLoader)) {
            unpackSolrCoreDir(fs.getPath("/"), solrHome);
        }
    } else {
        throw new IllegalArgumentException(
                "Packaged solrCoreBundle '" + solrCoreBundle + "' has unsupported type: " + contentType);
    }
}