Example usage for java.nio.file Files size

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

Introduction

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

Prototype

public static long size(Path path) throws IOException 

Source Link

Document

Returns the size of a file (in bytes).

Usage

From source file:uk.ac.ebi.eva.pipeline.jobs.AnnotationJobTest.java

@Test
public void noVariantsToAnnotateOnlyFindVariantsToAnnotateStepShouldRun() throws Exception {

    JobExecution jobExecution = jobLauncherTestUtils.launchJob();

    assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
    assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());

    Assert.assertEquals(1, jobExecution.getStepExecutions().size());
    StepExecution findVariantsToAnnotateStep = new ArrayList<>(jobExecution.getStepExecutions()).get(0);

    assertEquals(FIND_VARIANTS_TO_ANNOTATE, findVariantsToAnnotateStep.getStepName());

    assertTrue(vepInputFile.exists());/*from  ww  w  .j  a v  a 2  s .c  o  m*/
    assertTrue(Files.size(Paths.get(vepInputFile.toPath().toUri())) == 0);
}

From source file:edu.mit.lib.handbag.Controller.java

public void initialize() {

    Image wfIm = new Image(getClass().getResourceAsStream("/SiteMap.png"));
    workflowLabel.setGraphic(new ImageView(wfIm));
    workflowLabel.setContentDisplay(ContentDisplay.BOTTOM);

    workflowChoiceBox.addEventHandler(ActionEvent.ACTION, event -> {
        if (workflowChoiceBox.getItems().size() != 0) {
            return;
        }/* ww w. ja  v a  2s.com*/
        ObservableList<Workflow> wflowList = FXCollections.observableArrayList(loadWorkflows());
        workflowChoiceBox.setItems(wflowList);
        workflowChoiceBox.getSelectionModel().selectedIndexProperty().addListener((ov, value, new_value) -> {
            int newVal = (int) new_value;
            if (newVal != -1) {
                Workflow newSel = workflowChoiceBox.getItems().get(newVal);
                if (newSel != null) {
                    workflowLabel.setText(newSel.getName());
                    generateBagName(newSel.getBagNameGenerator());
                    bagLabel.setText(bagName);
                    sendButton.setText(newSel.getDestinationName());
                    setMetadataList(newSel);
                }
            }
        });
    });

    Image bagIm = new Image(getClass().getResourceAsStream("/Bag.png"));
    bagLabel.setGraphic(new ImageView(bagIm));
    bagLabel.setContentDisplay(ContentDisplay.BOTTOM);

    Image sendIm = new Image(getClass().getResourceAsStream("/Cabinet.png"));
    sendButton.setGraphic(new ImageView(sendIm));
    sendButton.setContentDisplay(ContentDisplay.BOTTOM);
    sendButton.setDisable(true);
    sendButton.setOnAction(e -> transmitBag());

    Image trashIm = new Image(getClass().getResourceAsStream("/Bin.png"));
    trashButton.setGraphic(new ImageView(trashIm));
    trashButton.setContentDisplay(ContentDisplay.BOTTOM);
    trashButton.setDisable(true);
    trashButton.setOnAction(e -> reset(false));

    TreeItem<PathRef> rootItem = new TreeItem<>(new PathRef("", Paths.get("data")));
    rootItem.setExpanded(true);
    payloadTreeView.setRoot(rootItem);
    payloadTreeView.setOnDragOver(event -> {
        if (event.getGestureSource() != payloadTreeView && event.getDragboard().getFiles().size() > 0) {
            event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
        }
        event.consume();
    });
    payloadTreeView.setOnDragDropped(event -> {
        Dragboard db = event.getDragboard();
        boolean success = false;
        if (db.getFiles().size() > 0) {
            for (File dragFile : db.getFiles()) {
                if (dragFile.isDirectory()) {
                    // explode directory and add expanded relative paths to tree
                    relPathSB = new StringBuilder();
                    try {
                        Files.walkFileTree(dragFile.toPath(), new SimpleFileVisitor<Path>() {
                            @Override
                            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                    throws IOException {
                                relPathSB.append(dir.getFileName()).append("/");
                                return FileVisitResult.CONTINUE;
                            }

                            @Override
                            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                    throws IOException {
                                payloadTreeView.getRoot().getChildren()
                                        .add(new TreeItem<>(new PathRef(relPathSB.toString(), file)));
                                bagSize += Files.size(file);
                                return FileVisitResult.CONTINUE;
                            }
                        });
                    } catch (IOException ioe) {
                    }
                } else {
                    payloadTreeView.getRoot().getChildren()
                            .add(new TreeItem<>(new PathRef("", dragFile.toPath())));
                    bagSize += dragFile.length();
                }
            }
            bagSizeLabel.setText(scaledSize(bagSize, 0));
            success = true;
            updateButtons();
        }
        event.setDropCompleted(success);
        event.consume();
    });

    metadataPropertySheet.setModeSwitcherVisible(false);
    metadataPropertySheet.setDisable(false);
    metadataPropertySheet.addEventHandler(KeyEvent.ANY, event -> {
        checkComplete(metadataPropertySheet.getItems());
        event.consume();
    });
}

From source file:com.cirrus.server.osgi.service.local.LocalStorageService.java

private ICirrusData createCirrusDataFromFile(final Path path) throws IOException {
    if (Files.isDirectory(path)) {
        return new CirrusFolderData(path.toString());
    } else {//from ww w.ja  v a2s  .c o m
        return new CirrusFileData(path.toString(), Files.size(path));
    }
}

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

protected LongObjectId putContent(Path f) throws FileNotFoundException, IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        LongObjectId id1, id2;//  w w w .ja va2  s . c  o  m
        String hexId1, hexId2;
        try (DigestInputStream in = new DigestInputStream(new BufferedInputStream(Files.newInputStream(f)),
                Constants.newMessageDigest())) {
            InputStreamEntity entity = new InputStreamEntity(in, Files.size(f),
                    ContentType.APPLICATION_OCTET_STREAM);
            id1 = LongObjectIdTestUtils.hash(f);
            hexId1 = id1.name();
            HttpPut request = new HttpPut(server.getURI() + "/lfs/objects/" + hexId1);
            request.setEntity(entity);
            HttpResponse response = client.execute(request);
            checkResponseStatus(response);
            id2 = LongObjectId.fromRaw(in.getMessageDigest().digest());
            hexId2 = id2.name();
            assertEquals(hexId1, hexId2);
        }
        return id1;
    }
}

From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java

@SuppressWarnings("serial")
protected void addStaticResource(final String mapping, final Path file) {

    if (!Files.isRegularFile(file)) {
        final FileNotFoundException fnf = new FileNotFoundException(file.toString());
        fnf.fillInStackTrace();//from   w ww  . ja  v a2 s .  c o m
        throw new IllegalArgumentException(fnf);
    }

    String md5;
    try {
        final InputStream is = file.toUri().toURL().openStream();
        md5 = computeMd5(is);
        is.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
    final String fMd5 = md5;

    addServlet(mapping, new HttpServlet() {
        @Override
        protected void service(final HttpServletRequest req, final HttpServletResponse resp)
                throws ServletException, IOException {
            resp.setContentLength((int) Files.size(file));
            resp.setHeader("Content-MD5", fMd5);
            final String mime = Files.probeContentType(file);
            if (mime != null) {
                resp.setContentType(mime);
            }
            final OutputStream out = resp.getOutputStream();
            Files.copy(file, out);
            out.flush();
        }
    });
}

From source file:org.eclipse.jdt.ls.core.internal.managers.InvisibleProjectImporter.java

private static File findNearbyNonEmptyFile(File nioFile) throws IOException {
    java.nio.file.Path directory = nioFile.getParentFile().toPath();
    try (Stream<java.nio.file.Path> walk = Files.walk(directory, 1)) {
        Optional<java.nio.file.Path> found = walk.filter(Files::isRegularFile).filter(file -> {
            try {
                return file.toString().endsWith(".java")
                        && !Objects.equals(nioFile.getName(), file.toFile().getName()) && Files.size(file) > 0;
            } catch (IOException e) {
                return false;
            }//www  .  ja v  a  2 s  .  c  om
        }).findFirst();

        if (found.isPresent()) {
            return found.get().toFile();
        }
    } catch (IOException e) {
    }

    return null;
}

From source file:org.digidoc4j.DataFile.java

/**
 * Returns the data file size.//  w ww  . j av a 2 s .com
 *
 * @return file size in bytes
 */
public long getFileSize() {
    logger.debug("");
    long fileSize;
    if (document instanceof StreamDocument || document instanceof FileDocument) {
        try {
            fileSize = Files.size(Paths.get(document.getAbsolutePath()));
            logger.debug("Document size: " + fileSize);
            return fileSize;
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new DigiDoc4JException(e);
        }
    }
    fileSize = getBytes().length;
    logger.debug("File document size: " + fileSize);
    return fileSize;
}

From source file:dk.dma.msiproxy.common.repo.RepositoryService.java

/**
 * Streams the file specified by the path
 * @param path the path/*from w ww .j  a  va 2  s .  com*/
 * @param request the servlet request
 * @return the response
 */
@GET
@javax.ws.rs.Path("/file/{file:.+}")
public Response streamFile(@PathParam("file") String path, @Context Request request) throws IOException {

    Path f = repoRoot.resolve(path);

    if (Files.notExists(f) || Files.isDirectory(f)) {
        log.warn("Failed streaming file: " + f);
        return Response.status(404).build();
    }

    // Set expiry to cacheTimeout minutes
    Date expirationDate = new Date(System.currentTimeMillis() + 1000L * 60L * cacheTimeout);

    String mt = fileTypes.getContentType(f);

    // Check for an ETag match
    EntityTag etag = new EntityTag("" + Files.getLastModifiedTime(f).toMillis() + "_" + Files.size(f), true);
    Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(etag);
    if (responseBuilder != null) {
        // Etag match
        log.trace("File unchanged. Return code 304");
        return responseBuilder.expires(expirationDate).build();
    }

    log.trace("Streaming file: " + f);
    return Response.ok(f.toFile(), mt).expires(expirationDate).tag(etag).build();
}

From source file:org.darkware.wpman.config.ReloadableWordpressConfig.java

/**
 * Load a plugin profile fragment and apply it as an override.
 *
 * @param plugins The {@link PluginListConfig} to load the profile fragment into
 * @param pluginFile The file containing the profile fragment.
 *//*from ww w.j a va  2  s .c o m*/
protected void loadPlugin(final PluginListConfig plugins, final Path pluginFile) {
    try {
        PluginConfig plug;
        if (Files.size(pluginFile) < 3)
            plug = new PluginConfig();
        else
            plug = this.mapper.readValue(pluginFile.toFile(), PluginConfig.class);

        // Set the source file
        plug.setPolicyFile(pluginFile);

        String slug = ReloadableWordpressConfig.slugForFile(pluginFile);

        plugins.overrideItem(slug, plug);
        WPManager.log.debug("Loaded configuration for plugin: {}", slug);
    } catch (JsonMappingException e) {
        WPManager.log.warn("Skipped loading plugin configuration (formatting): {}", pluginFile);
    } catch (IllegalSlugException e) {
        WPManager.log.warn("Skipped loading plugin configuration (illegal slug): {}", pluginFile, e);
    } catch (IOException e) {
        WPManager.log.error("Error loading plugin configuration: {}", pluginFile, e);
    }
}

From source file:com.spotify.scio.util.RemoteFileUtil.java

private Path downloadImpl(URI src) {
    try {//from   w w w  .  ja v a  2 s .  c  om
        Path dst = getDestination(src);

        if (src.getScheme() == null || src.getScheme().equals("file")) {
            // Local URI
            Path srcPath = src.getScheme() == null ? Paths.get(src.toString()) : Paths.get(src);
            if (Files.isSymbolicLink(dst) && Files.readSymbolicLink(dst).equals(srcPath)) {
                LOG.info("URI {} already symlink-ed", src);
            } else {
                Files.createSymbolicLink(dst, srcPath);
                LOG.info("Symlink-ed {} to {}", src, dst);
            }
        } else {
            // Remote URI
            long srcSize = getRemoteSize(src);
            boolean shouldDownload = true;
            if (Files.exists(dst)) {
                long dstSize = Files.size(dst);
                if (srcSize == dstSize) {
                    LOG.info("URI {} already downloaded", src);
                    shouldDownload = false;
                } else {
                    LOG.warn("Destination exists with wrong size. {} [{}B] -> {} [{}B]", src, srcSize, dst,
                            dstSize);
                    Files.delete(dst);
                }
            }
            if (shouldDownload) {
                copyToLocal(src, dst);
                LOG.info("Downloaded {} -> {} [{}B]", src, dst, srcSize);
            }
        }

        return dst;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}