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:de.bluepair.sci.client.SHAUtils.java

public static <T> Map<String, String> sha512(Path path, Predicate<T> gard, T testValue, long blockSizePref,
        boolean forceBlockSize) {

    if (Files.notExists(path)) {
        return null;
    }/*from   ww  w .ja v a  2s.  c  om*/
    MessageDigest md = getDigest();
    MessageDigest md1 = getDigest();

    if (!gard.test(testValue)) {
        return null;
    }
    long blockSize = blockSizePref;
    long size = -1;
    try {
        size = Files.size(path);
        if (!forceBlockSize) {// maximal 10 hashsummen
            // sonst hab ich zu viele in der datei
            // stehen!
            while (size / blockSize > 10) {
                blockSize += blockSizePref;
            }
        }

    } catch (IOException e) {
        blockSize = blockSizePref;
        return null;
    }

    Map<String, String> map = new HashMap<>();

    long lastStart = 0;

    long stepDown = blockSize;

    try (final SeekableByteChannel fileChannel = Files.newByteChannel(path, StandardOpenOption.READ);) {

        final ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
        int last;
        do {
            if (!gard.test(testValue) || Files.notExists(path)) {
                return null;
            }
            buffer.clear();
            last = fileChannel.read(buffer);

            buffer.flip();
            md.update(buffer);

            // calc 2checksups
            buffer.flip();
            md1.update(buffer);

            if (last > 0) {
                stepDown -= last;
            }

            // wenn ich ein 100mb netzwerk habe
            // ~ca. 5MB bertragung
            // also bei abbruch kann wiederaufgesetzt werden wenn die summen
            // bekannt sind.
            // ~hnlich Blcke berechen also
            // 0-5 c1
            // 0-10 c2
            // 5-10 c3 ...

            if (stepDown <= 0 || (last <= 0)) {
                long len = (blockSize + Math.abs(stepDown));
                if (stepDown > 0) {
                    // kottektur wenn last <0
                    len = blockSize - stepDown;
                }
                stepDown = blockSize;
                map.put("sha512_" + lastStart + "_" + len, Hex.encodeHexString(md1.digest()));
                lastStart += len;
                md1.reset();
            }

        } while (last > 0);

    } catch (IOException ex) {
        Logger.getLogger(FileAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

    final byte[] sha1hash = md.digest();
    map.put("sha512", Hex.encodeHexString(sha1hash));
    return map;

}

From source file:com.liferay.sync.engine.util.FileUtil.java

public static boolean hasFileChanged(SyncFile syncFile, Path filePath) throws IOException {

    if (filePath == null) {
        return true;
    }//from   ww  w  . j  a v a2 s  . c o  m

    if ((syncFile.getSize() > 0) && (syncFile.getSize() != Files.size(filePath))) {

        return true;
    }

    String checksum = getChecksum(filePath);

    return !checksum.equals(syncFile.getChecksum());
}

From source file:feign.form.BasicClientTest.java

@Test
public void testUpload() throws Exception {
    val path = Paths.get(this.getClass().getClassLoader().getResource("file.txt").toURI());
    Assert.assertTrue(Files.exists(path));

    val stringResponse = api.upload(10, Boolean.TRUE, path.toFile());
    Assert.assertEquals(Files.size(path), Long.parseLong(stringResponse));
}

From source file:org.sejda.core.service.OptimizeTaskTest.java

private long sizeOfResult(Path p) {
    try {//from  ww  w .  jav  a 2s. c  om
        return Files.size(p) / 1000;
    } catch (IOException e) {
        LOG.error("Test failed", e);
        fail(e.getMessage());
    }
    return 0;
}

From source file:sonicScream.services.SettingsService.java

public SettingsService(Path settingsFile, Path crcFile, Path profilesDirectory) throws IOException {
    try {// www  .j  a  v  a  2  s . c om
        JAXBContext context = JAXBContext.newInstance(SettingsMapWrapper.class);
        Unmarshaller um = context.createUnmarshaller();

        if (Files.size(settingsFile) == 0) {
            _settingsDictionary = new HashMap<>();
        } else {
            _settingsDictionary = ((SettingsMapWrapper) um.unmarshal(Files.newInputStream(settingsFile)))
                    .getSettingsMap();
        }

        context = JAXBContext.newInstance(CRCsMapWrapper.class);
        um = context.createUnmarshaller();

        if (Files.size(crcFile) == 0) {
            _crcDictionary = new HashMap<>();
        } else {
            _crcDictionary = ((CRCsMapWrapper) um.unmarshal(Files.newInputStream(crcFile))).getCRCsMap();
        }

        context = JAXBContext.newInstance(Profile.class);
        um = context.createUnmarshaller();
        final Unmarshaller finalUm = um;

        _profileList = new ArrayList();
        List<Path> profileFolders = FilesEx.getDirectories(profilesDirectory);
        for (Path folder : profileFolders) {
            File file = FileUtils.listFiles(folder.toFile(), new String[] { "xml" }, false).stream().findFirst()
                    .orElse(null);
            if (file != null) {
                try {
                    Profile profile = (Profile) finalUm.unmarshal(new FileInputStream(file));
                    _profileList.add(profile);
                } catch (IOException | JAXBException ex) {
                    System.err.printf("Unable to read profile %s: %s", file.toString(), ex.getMessage());
                }
            }
        }
    } catch (JAXBException ex) {
        //TODO: Error message
        ex.printStackTrace();
    }
}

From source file:com.kamike.misc.FsUtils.java

public static long fileSize(String src) {
    long ret = 0L;
    try {//ww w .  j av a  2  s . co  m
        Path source = Paths.get(src);

        ret = Files.size(source);

    } catch (IOException ex) {
        Logger.getLogger(FsUtils.class.getName()).log(Level.SEVERE, null, ex);
        ret = 0L;
    }
    return ret;
}

From source file:org.apache.nifi.minifi.FlowParser.java

/**
 * Generates a {@link Document} from the flow configuration file provided
 *//*from  w w w .  j ava2  s .  co m*/
public Document parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));
        return document;

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}

From source file:org.wte4j.examples.showcase.server.hsql.ShowCaseDbInitializerTest.java

@Test
public void createDatabaseFilesWithoutOveride() throws IOException, SQLException {
    ApplicationContext context = new StaticApplicationContext();
    Path directory = Files.createTempDirectory("database");
    Path dummyFile = directory.resolve("wte4j-showcase.script");
    Files.createFile(dummyFile);/*www  .j  a v a 2s  .c o  m*/
    try {
        ShowCaseDbInitializer showCaseDbInitializer = new ShowCaseDbInitializer(context);
        showCaseDbInitializer.createDateBaseFiles(directory, false);

        Set<String> fileNamesInDirectory = listFiles(directory);
        Set<String> expectedFileNames = new HashSet<String>();
        expectedFileNames.add("wte4j-showcase.script");
        assertEquals(expectedFileNames, fileNamesInDirectory);
        assertEquals(0, Files.size(dummyFile));
    } finally {
        deleteDirectory(directory);
    }
}

From source file:org.apache.nifi.authorization.FlowParser.java

/**
 * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts
 * the root group input ports and output ports, and their access controls.
 *
 *//*from  w w w.  j a v  a  2s.  co m*/
public FlowInfo parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        // create validating document builder
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(flowSchema);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));

        // extract the root group id
        final Element rootElement = document.getDocumentElement();

        final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0);
        if (rootGroupElement == null) {
            logger.warn("rootGroup element not found in Flow Configuration file");
            return null;
        }

        final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0);
        if (rootGroupIdElement == null) {
            logger.warn("id element not found under rootGroup in Flow Configuration file");
            return null;
        }

        final String rootGroupId = rootGroupIdElement.getTextContent();

        final List<PortDTO> ports = new ArrayList<>();
        ports.addAll(getPorts(rootGroupElement, "inputPort"));
        ports.addAll(getPorts(rootGroupElement, "outputPort"));

        return new FlowInfo(rootGroupId, ports);

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}

From source file:fr.duminy.jbackup.core.archive.FileCollector.java

private void collectFilesImpl(List<SourceWithPath> collectedFiles, Collection<ArchiveParameters.Source> sources,
        MutableLong totalSize, Cancellable cancellable) throws IOException {
    totalSize.setValue(0L);/*w w  w  . j  ava  2 s  .c o m*/

    for (ArchiveParameters.Source source : sources) {
        Path sourcePath = source.getSource();
        if (!sourcePath.isAbsolute()) {
            throw new IllegalArgumentException(String.format("The file '%s' is relative.", sourcePath));
        }

        long size;

        if (Files.isDirectory(sourcePath)) {
            size = collect(collectedFiles, sourcePath, source.getDirFilter(), source.getFileFilter(),
                    cancellable);
        } else {
            collectedFiles.add(new SourceWithPath(sourcePath, sourcePath));
            size = Files.size(sourcePath);
        }

        totalSize.add(size);
    }
}