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:com.spectralogic.ds3client.integration.PutJobManagement_Test.java

@Test
public void cancelJobWithForce() throws Exception {

    final int testTimeOutSeconds = 5;

    final String book1 = "beowulf.txt";
    final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1);
    final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1));
    final Ds3Object obj2 = new Ds3Object("place_holder", 5000000);

    try {/*from  w w w.j  ava  2 s.c  o m*/
        final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(obj1, obj2));
        final UUID jobId = putJob.getJobId();
        final SeekableByteChannel book1Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME)
                .buildChannel(book1);

        client.putObject(
                new PutObjectRequest(BUCKET_NAME, book1, book1Channel, jobId, 0, Files.size(objPath1)));
        ABMTestHelper.waitForJobCachedSizeToBeMoreThanZero(jobId, client, 20);

        final CancelJobSpectraS3Response responseWithForce = client
                .cancelJobSpectraS3(new CancelJobSpectraS3Request(jobId.toString()));
        assertEquals(responseWithForce.getStatusCode(), 204);

        //Allow for lag time before canceled job appears~1.5 seconds in unloaded system
        final long startTimeCanceledUpdate = System.nanoTime();
        boolean jobCanceled = false;
        while (!jobCanceled) {
            Thread.sleep(500);
            final GetCanceledJobsSpectraS3Response canceledJobs = client
                    .getCanceledJobsSpectraS3(new GetCanceledJobsSpectraS3Request());
            for (final CanceledJob canceledJob : canceledJobs.getCanceledJobListResult().getCanceledJobs()) {
                if (canceledJob.getId().equals(jobId)) {
                    jobCanceled = true;
                }
            }
            assertThat((System.nanoTime() - startTimeCanceledUpdate) / 1000000000,
                    lessThan((long) testTimeOutSeconds));
        }

    } finally {
        deleteAllContents(client, BUCKET_NAME);
    }
}

From source file:org.roda.core.storage.fs.FileStorageService.java

@Override
public Binary createBinary(StoragePath storagePath, ContentPayload payload, boolean asReference)
        throws GenericException, AlreadyExistsException {
    if (asReference) {
        throw new GenericException("Method not yet implemented");
    } else {/*from   w  w  w .j av a  2s. c om*/
        Path binPath = FSUtils.getEntityPath(basePath, storagePath);
        if (FSUtils.exists(binPath)) {
            throw new AlreadyExistsException("Binary already exists: " + binPath);
        } else {

            try {
                // ensuring parent exists
                Path parent = binPath.getParent();
                if (!FSUtils.exists(parent)) {
                    Files.createDirectories(parent);
                }

                // writing file
                payload.writeToPath(binPath);
                ContentPayload newPayload = new FSPathContentPayload(binPath);
                Long sizeInBytes = Files.size(binPath);
                boolean isReference = false;
                Map<String, String> contentDigest = null;

                return new DefaultBinary(storagePath, newPayload, sizeInBytes, isReference, contentDigest);
            } catch (FileAlreadyExistsException e) {
                throw new AlreadyExistsException("Binary already exists: " + binPath);
            } catch (IOException e) {
                throw new GenericException("Could not create binary", e);
            }
        }
    }
}

From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

private boolean isPathFullyAccessible(Path path) {
    if (!Files.exists(path)) {
        return false;
    }// ww  w.ja v a 2s  .c  o m

    if (Files.isDirectory(path)) {
        DirectoryStream<Path> directoryStream = null;
        try {
            directoryStream = Files.newDirectoryStream(path);

            return true;
        } catch (IOException e) {
            log.debug("Unaccessible directory: {}", path, e);
            return false;
        } finally {
            IOUtils.closeQuietly(directoryStream);
        }

    } else {
        FileChannel fileChannel = null;
        try {
            fileChannel = FileChannel.open(path, StandardOpenOption.READ);
            fileChannel.position(Files.size(path));

            return true;
        } catch (IOException e) {
            log.debug("Unaccessible file: {}", path, e);
            return false;
        } finally {
            IOUtils.closeQuietly(fileChannel);
        }
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public StreamContent preview(String backendPath, Dimension maxPreviewDim) throws C5CException {
    Path file = buildRealPath(backendPath);
    try {//from w  w  w  .java  2s .  c o m
        Dimension currentDim = UserObjectProxy.getDimension(Files.newInputStream(file));
        if (maxPreviewDim != null
                && (currentDim.width > maxPreviewDim.width || currentDim.height > maxPreviewDim.height)) {
            return resize(new BufferedInputStream(Files.newInputStream(file)),
                    FilenameUtils.getExtension(backendPath), maxPreviewDim);
        }
        return buildStreamContent(Files.newInputStream(file), Files.size(file));
    } catch (IOException e) {
        throw new C5CException(FilemanagerAction.PREVIEW, e.getMessage());
    }
}

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

/**
 * Returns a list of files in the folder specified by the clientId
 * @return the list of files in the folder specified by the path
 *//*ww  w  . j  av  a 2  s  .c  o m*/
@RequestMapping(value = "/list/{clientId:.*}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public List<RepoFile> listFiles(@PathVariable("clientId") String clientId) throws IOException {

    List<RepoFile> result = new ArrayList<>();
    Path folder = repoRoot.resolve(clientId);

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

        // Filter out directories and hidden files
        DirectoryStream.Filter<Path> filter = file -> Files.isRegularFile(file)
                && !file.getFileName().toString().startsWith(".");

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder, filter)) {
            stream.forEach(f -> {
                RepoFile vo = new RepoFile();
                vo.setName(f.getFileName().toString());
                vo.setPath(clientId + "/" + f.getFileName().toString());
                try {
                    vo.setUpdated(new Date(Files.getLastModifiedTime(f).toMillis()));
                    vo.setSize(Files.size(f));
                } catch (Exception e) {
                    log.finer("Error reading file attribute for " + f);
                }
                vo.setComplete(!f.getFileName().toString().endsWith(DOWNLOAD_SUFFIX));
                result.add(vo);
            });
        }
    }
    Collections.sort(result);
    return result;
}

From source file:org.roda.core.storage.fs.FileStorageService.java

@Override
public Binary createRandomBinary(StoragePath parentStoragePath, ContentPayload payload, boolean asReference)
        throws GenericException, RequestNotValidException {
    if (asReference) {
        throw new GenericException("Method not yet implemented");
    } else {//from   www  .j ava2 s  .com
        Path parent = FSUtils.getEntityPath(basePath, parentStoragePath);
        try {
            // ensure parent exists
            if (!FSUtils.exists(parent)) {
                Files.createDirectories(parent);
            }

            // create file
            Path binPath = FSUtils.createRandomFile(parent);

            // writing file
            payload.writeToPath(binPath);
            StoragePath storagePath = FSUtils.getStoragePath(basePath, binPath);
            ContentPayload newPayload = new FSPathContentPayload(binPath);
            Long sizeInBytes = Files.size(binPath);
            boolean isReference = false;
            Map<String, String> contentDigest = null;

            return new DefaultBinary(storagePath, newPayload, sizeInBytes, isReference, contentDigest);
        } catch (IOException e) {
            throw new GenericException("Could not create binary", e);
        }
    }
}

From source file:org.vpac.web.controller.DataController.java

@RequestMapping(value = "/Download/{taskId}", method = RequestMethod.GET)
public void downloadFile(@PathVariable("taskId") String taskId, HttpServletResponse response)
        throws TaskException, FileNotFoundException {
    // get your file as InputStream
    Path p = Exporter.findOutputPath(taskId);
    FileInputStream is = new FileInputStream(p.toFile());
    try {/*from w w  w  .  j  ava2  s .  com*/
        // Send headers, such as file name and length. The length is
        // required for streaming to work properly; see
        // http://stackoverflow.com/questions/10552555/response-flushbuffer-is-not-working
        // Not using response.setContentLength(int), because the file may be
        // larger than 2GB, in which case an int would overflow.
        response.setContentType("application-xdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + p.getFileName().toString());
        response.setHeader("Content-Length", String.format("%d", Files.size(p)));
        response.flushBuffer();
        // Copy file to response's OutputStream (send it to the client)
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        log.warn("IO error writing file to output stream. User may " + "have cancelled.");
    }
}

From source file:com.liferay.sync.engine.document.library.util.FileEventUtil.java

public static void retryFileTransfers(long syncAccountId) throws IOException {

    List<SyncFile> deletingSyncFiles = SyncFileService.findSyncFiles(syncAccountId,
            SyncFile.UI_EVENT_DELETED_LOCAL, "syncFileId", true);

    for (SyncFile deletingSyncFile : deletingSyncFiles) {
        if (!FileUtil.notExists(Paths.get(deletingSyncFile.getFilePathName()))) {

            deletingSyncFile.setState(SyncFile.STATE_SYNCED);
            deletingSyncFile.setUiEvent(SyncFile.UI_EVENT_NONE);

            SyncFileService.update(deletingSyncFile);

            continue;
        }/*  ww  w.  j  a  va2s  . c o  m*/

        if (deletingSyncFile.isFolder()) {
            deleteFolder(syncAccountId, deletingSyncFile);
        } else {
            deleteFile(syncAccountId, deletingSyncFile);
        }
    }

    List<SyncFile> downloadingSyncFiles = SyncFileService.findSyncFiles(syncAccountId,
            SyncFile.UI_EVENT_DOWNLOADING, "size", true);

    for (SyncFile downloadingSyncFile : downloadingSyncFiles) {
        downloadFile(syncAccountId, downloadingSyncFile);
    }

    BatchEventManager.fireBatchDownloadEvents();

    List<SyncFile> uploadingSyncFiles = SyncFileService.findSyncFiles(syncAccountId,
            SyncFile.UI_EVENT_UPLOADING, "size", true);

    for (SyncFile uploadingSyncFile : uploadingSyncFiles) {
        Path filePath = Paths.get(uploadingSyncFile.getFilePathName());

        if (FileUtil.notExists(filePath)) {
            if (uploadingSyncFile.getTypePK() == 0) {
                SyncFileService.deleteSyncFile(uploadingSyncFile, false);
            }

            continue;
        }

        if (uploadingSyncFile.isFolder()) {
            if (uploadingSyncFile.getTypePK() > 0) {
                updateFolder(filePath, uploadingSyncFile.getSyncAccountId(), uploadingSyncFile);
            } else {
                addFolder(uploadingSyncFile.getParentFolderId(), uploadingSyncFile.getRepositoryId(),
                        syncAccountId, uploadingSyncFile.getName(), uploadingSyncFile);
            }

            continue;
        }

        String checksum = FileUtil.getChecksum(filePath);

        uploadingSyncFile.setChecksum(checksum);

        uploadingSyncFile.setSize(Files.size(filePath));

        SyncFileService.update(uploadingSyncFile);

        IODeltaUtil.checksums(uploadingSyncFile);

        if (uploadingSyncFile.getTypePK() > 0) {
            updateFile(filePath, syncAccountId, uploadingSyncFile, null, uploadingSyncFile.getName(), "", null,
                    0, checksum);
        } else {
            addFile(filePath, uploadingSyncFile.getParentFolderId(), uploadingSyncFile.getRepositoryId(),
                    syncAccountId, checksum, uploadingSyncFile.getName(), uploadingSyncFile.getMimeType(),
                    uploadingSyncFile);
        }
    }

    List<SyncFile> movingSyncFiles = SyncFileService.findSyncFiles(syncAccountId, SyncFile.UI_EVENT_MOVED_LOCAL,
            "syncFileId", true);

    for (SyncFile movingSyncFile : movingSyncFiles) {
        if (movingSyncFile.isFolder()) {
            moveFolder(movingSyncFile.getParentFolderId(), syncAccountId, movingSyncFile);
        } else {
            moveFile(movingSyncFile.getParentFolderId(), syncAccountId, movingSyncFile);
        }
    }

    BatchEventManager.fireBatchEvents();

    List<SyncFile> resyncingSyncFiles = SyncFileService.findSyncFiles(syncAccountId,
            SyncFile.UI_EVENT_RESYNCING, "syncFileId", true);

    for (SyncFile resyncingSyncFile : resyncingSyncFiles) {
        resyncFolder(syncAccountId, resyncingSyncFile);
    }
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private ContentItem readContent(URI uri) throws StorageException {
    Path file = getContentFilePath(uri);

    if (file == null) {
        throw new StorageException("Unable to find file for content ID: " + uri.getSchemeSpecificPart());
    }//from  w  w w  . ja  v a 2s. co  m

    String extension = FilenameUtils.getExtension(file.getFileName().toString());

    String mimeType;

    try (InputStream fileInputStream = Files.newInputStream(file)) {
        mimeType = mimeTypeMapper.guessMimeType(fileInputStream, extension);
    } catch (Exception e) {
        LOGGER.warn("Could not determine mime type for file extension = {}; defaulting to {}", extension,
                DEFAULT_MIME_TYPE);
        mimeType = DEFAULT_MIME_TYPE;
    }
    if (mimeType == null || DEFAULT_MIME_TYPE.equals(mimeType)) {
        try {
            mimeType = Files.probeContentType(file);
        } catch (IOException e) {
            LOGGER.warn("Unable to determine mime type using Java Files service.", e);
            mimeType = DEFAULT_MIME_TYPE;
        }
    }

    LOGGER.debug("mimeType = {}", mimeType);
    long size = 0;
    try {
        size = Files.size(file);
    } catch (IOException e) {
        LOGGER.warn("Unable to retrieve size of file: {}", file.toAbsolutePath().toString(), e);
    }
    return new ContentItemImpl(uri.getSchemeSpecificPart(), uri.getFragment(),
            com.google.common.io.Files.asByteSource(file.toFile()), mimeType, file.getFileName().toString(),
            size, null);
}

From source file:ste.xtest.net.StubURLConnection.java

private String getContentLength(final Object content) {
    long len = -1;

    if (content == null) {
        len = 0;//from  w ww  .  java2  s.  c o m
    } else {
        if (content instanceof byte[]) {
            len = ((byte[]) content).length;
        } else if (content instanceof String) {
            len = ((String) content).length();
        } else if (content instanceof Path) {
            try {
                len = Files.size((Path) content);
            } catch (IOException x) {
                //
                // nothing to do, it will take -1
                //
            }
        }
    }

    return String.valueOf(len);
}