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:org.freeeed.main.ActionStaging.java

private long dirSize(Path path) {
    long size = 0;
    try {/*ww  w  . j  a v a  2 s.  c  o m*/
        DirectoryStream ds = Files.newDirectoryStream(path);
        for (Object o : ds) {
            Path p = (Path) o;
            if (Files.isDirectory(p)) {
                size += dirSize(p);
            } else {
                size += Files.size(p);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Dir size calculation error", e);
    }
    return size;
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest,
        SyncFile syncFile) throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
        _syncTrafficShapingHandler.decrementConnectionsCount();

        if (_logger.isTraceEnabled()) {
            Channel channel = channelHandlerContext.channel();

            _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
        }//  w w w.j a  v  a 2 s.  c  om

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    if (_logger.isDebugEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
        modifiedTime = modifiedTime / 1000 * 1000;
        previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

        _syncTrafficShapingHandler.decrementConnectionsCount();

        Channel channel = channelHandlerContext.channel();

        _logger.error(
                "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}",
                channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime);

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
        httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile),
            channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
                return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
        }

    });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

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

/**
 * Creates a file with random content, repeatedly writing a random string of
 * 4k length to the file until the file has at least the specified length.
 *
 * @param f//  w  w  w .j  av  a  2  s  .c o  m
 *            file to fill
 * @param size
 *            size of the file to generate
 * @return length of the generated file in bytes
 * @throws IOException
 */
protected long createPseudoRandomContentFile(Path f, long size) throws IOException {
    SecureRandom rnd = new SecureRandom();
    byte[] buf = new byte[4096];
    rnd.nextBytes(buf);
    ByteBuffer bytebuf = ByteBuffer.wrap(buf);
    try (FileChannel outChannel = FileChannel.open(f, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {
        long len = 0;
        do {
            len += outChannel.write(bytebuf);
            if (bytebuf.position() == 4096) {
                bytebuf.rewind();
            }
        } while (len < size);
    }
    return Files.size(f);
}

From source file:com.qwazr.library.archiver.ArchiverTool.java

public void extract(final Path sourceFile, final Path destDir) throws IOException, ArchiveException {
    try (final InputStream is = new BufferedInputStream(Files.newInputStream(sourceFile))) {
        try (final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is)) {
            ArchiveEntry entry;/*from w  w  w . jav  a  2  s  . com*/
            while ((entry = in.getNextEntry()) != null) {
                if (!in.canReadEntryData(entry))
                    continue;
                if (entry.isDirectory()) {
                    final Path newDir = destDir.resolve(entry.getName());
                    if (!Files.exists(newDir))
                        Files.createDirectory(newDir);
                    continue;
                }
                if (entry instanceof ZipArchiveEntry)
                    if (((ZipArchiveEntry) entry).isUnixSymlink())
                        continue;
                final Path destFile = destDir.resolve(entry.getName());
                final Path parentDir = destFile.getParent();
                if (!Files.exists(parentDir))
                    Files.createDirectories(parentDir);
                final long entryLastModified = entry.getLastModifiedDate().getTime();
                if (Files.exists(destFile) && Files.isRegularFile(destFile)
                        && Files.getLastModifiedTime(destFile).toMillis() == entryLastModified
                        && entry.getSize() == Files.size(destFile))
                    continue;
                IOUtils.copy(in, destFile);
                Files.setLastModifiedTime(destFile, FileTime.fromMillis(entryLastModified));
            }
        } catch (IOException e) {
            throw new IOException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
        }
    } catch (ArchiveException e) {
        throw new ArchiveException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
    }
}

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

/**
 * Returns a list of files in the folder specified by the path
 * @param path the path// w  w  w . ja  v  a2s . c om
 * @return the list of files in the folder specified by the path
 */
@GET
@javax.ws.rs.Path("/list/{folder:.+}")
@Produces("application/json;charset=UTF-8")
@NoCache
public List<Attachment> listFiles(@PathParam("folder") String path) throws IOException {

    List<Attachment> result = new ArrayList<>();
    Path folder = repoRoot.resolve(path);

    if (Files.exists(folder) && Files.isDirectory(folder)) {

        // Filter out directories, hidden files, thumbnails and map images
        DirectoryStream.Filter<Path> filter = file -> Files.isRegularFile(file)
                && !file.getFileName().toString().startsWith(".")
                && !file.getFileName().toString().matches(".+_thumb_\\d{1,3}\\.\\w+") && // Thumbnails
                !file.getFileName().toString().matches("map_\\d{1,3}\\.png"); // Map image

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder, filter)) {
            stream.forEach(f -> {
                Attachment vo = new Attachment();
                vo.setName(f.getFileName().toString());
                vo.setPath(WebUtils.encodeURI(path + "/" + f.getFileName().toString()));
                vo.setDirectory(Files.isDirectory(f));
                try {
                    vo.setUpdated(new Date(Files.getLastModifiedTime(f).toMillis()));
                    vo.setSize(Files.size(f));
                } catch (Exception e) {
                    log.trace("Error reading file attribute for " + f);
                }
                result.add(vo);
            });
        }
    }
    return result;
}

From source file:org.apache.karaf.tooling.ArchiveMojo.java

private void addFileToZip(ZipArchiveOutputStream tOut, Path f, String base) throws IOException {
    if (Files.isDirectory(f)) {
        String entryName = base + f.getFileName().toString() + "/";
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        tOut.putArchiveEntry(zipEntry);//from   w  w  w . j av a  2 s .com
        tOut.closeArchiveEntry();
        try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) {
            for (Path child : children) {
                addFileToZip(tOut, child, entryName);
            }
        }
    } else if (useSymLinks && Files.isSymbolicLink(f)) {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DEFAULT_FILE_PERM);
        tOut.putArchiveEntry(zipEntry);
        tOut.write(Files.readSymbolicLink(f).toString().getBytes());
        tOut.closeArchiveEntry();
    } else {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setSize(Files.size(f));
        if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin"))) {
            if (!entryName.endsWith(".bat")) {
                zipEntry.setUnixMode(0755);
            } else {
                zipEntry.setUnixMode(0644);
            }
        }
        tOut.putArchiveEntry(zipEntry);
        Files.copy(f, tOut);
        tOut.closeArchiveEntry();
    }
}

From source file:jonelo.jacksum.concurrent.Jacksum2Cli.java

private void loadFilesToHash(List<Path> allFiles, Map<Path, Long> fileSizes, Map<Path, Long> fileLastModified)
        throws IOException {

    final int maxDepth = this.recursive ? Integer.MAX_VALUE : 1;
    final FileSystem fs = FileSystems.getDefault();
    final FileVisitOption[] options = this.ignoreSymbolicLinksToDirectories ? new FileVisitOption[0]
            : new FileVisitOption[] { FileVisitOption.FOLLOW_LINKS };

    for (String filename : this.filenames) {
        Files.walk(fs.getPath(filename), maxDepth, options).filter(path -> Files.isRegularFile(path))
                .forEach(path -> {// ww w  . j  av  a2  s. c o  m
                    allFiles.add(path);
                    try {
                        fileSizes.put(path, Files.size(path));
                        fileLastModified.put(path, Files.getLastModifiedTime(path).toMillis());
                    } catch (IOException ioEx) {
                        fileSizes.put(path, -1l);
                        fileLastModified.put(path, 0l);
                    }
                });
    }

}

From source file:misc.FileHandler.java

/**
 * Returns a <code>MESSAGE_DIGEST</code> checksum of the given file.
 * //from   w ww  .  j  ava 2 s . c  o  m
 * @param file
 *            the file to checksum.
 * @return the checksum of the given file or <code>null</code>, if an error
 *         occurs.
 */
public static byte[] getChecksum(Path file) {
    if ((file == null) || !Files.isReadable(file)) {
        throw new IllegalArgumentException("file must exist and be readable!");
    }

    byte[] checksum = null;

    try (FileInputStream in = new FileInputStream(file.toFile());) {
        checksum = getChecksum(in, Files.size(file));
    } catch (IOException | NoSuchAlgorithmException e) {
        Logger.logError(e);
    }

    return checksum;
}

From source file:org.ulyssis.ipp.reader.Reader.java

/**
 * Perform cleanup on shutdown. (When the thread is interrupted.)
 *//*from  ww  w  .jav  a  2s.co m*/
private void shutdownHook() {
    statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.SHUTDOWN,
            String.format("Shutting down reader %s.", options.getId())));
    if (speedwayInitialized) {
        LOG.info("Shutting down reader!");
        boolean successfulStop = llrpReader.stop();
        if (!successfulStop) {
            LOG.error("Could not stop the Speedway!");
        } else {
            LOG.info("Successfully stopped the reader!");
        }
    }
    replayChannel.ifPresent(channel -> {
        final Path replayFile = options.getReplayFile().get();
        try {
            channel.close();
        } catch (IOException e) {
            LOG.error("Error while closing replay log file: {}.", replayFile, e);
        }
        try {
            if (Files.size(replayFile) == 0L) {
                LOG.info("Deleting empty replay file: {}", replayFile);
                Files.delete(replayFile);
            }
        } catch (IOException e) {
            LOG.error("Couldn't check size of replay log {}, or delete it.", replayFile, e);
        }
    });
    LOG.info("Bye bye!");
}

From source file:com.spectralogic.ds3client.helpers.FileSystemHelper_Test.java

private void putObjectThenRunVerification(final FileSystemHelper fileSystemHelper,
        final ResultVerifier resultVerifier) throws IOException, URISyntaxException {
    try {//from   w  ww  . j ava 2 s. co m
        final String DIR_NAME = "largeFiles/";
        final String[] FILE_NAMES = new String[] { "lesmis-copies.txt" };

        final Path dirPath = ResourceUtils.loadFileResource(DIR_NAME);

        final AtomicLong totalBookSizes = new AtomicLong(0);

        final List<String> bookTitles = new ArrayList<>();
        final List<Ds3Object> objects = new ArrayList<>();
        for (final String book : FILE_NAMES) {
            final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + book);
            final long bookSize = Files.size(objPath);
            totalBookSizes.getAndAdd(bookSize);
            final Ds3Object obj = new Ds3Object(book, bookSize);

            bookTitles.add(book);
            objects.add(obj);
        }

        final int maxNumBlockAllocationRetries = 1;
        final int maxNumObjectTransferAttempts = 1;
        final int retryDelay = -1;
        final Ds3ClientHelpers ds3ClientHelpers = new Ds3ClientHelpersImpl(client, maxNumBlockAllocationRetries,
                maxNumObjectTransferAttempts, retryDelay, new SameThreadEventRunner(), fileSystemHelper);

        final AtomicInteger numTimesCallbackCalled = new AtomicInteger(0);

        final Ds3ClientHelpers.Job writeJob = ds3ClientHelpers.startWriteJob(BUCKET_NAME, objects);
        writeJob.attachObjectCompletedListener(new ObjectCompletedListener() {
            @Override
            public void objectCompleted(final String name) {
                numTimesCallbackCalled.getAndIncrement();

                final ObjectStorageSpaceVerificationResult result = ds3ClientHelpers
                        .objectsFromBucketWillFitInDirectory(BUCKET_NAME, Arrays.asList(FILE_NAMES),
                                Paths.get("."));

                resultVerifier.verifyResult(result, totalBookSizes.get());
            }
        });

        writeJob.transfer(new FileObjectPutter(dirPath));

        assertEquals(1, numTimesCallbackCalled.get());
    } finally {
        deleteAllContents(client, BUCKET_NAME);
    }
}