Java Code Examples for java.nio.file.Files.size()

The following are Jave code examples for showing how to use size() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Photato   File: PhotatoVideo.java   View Source Code Vote up 6 votes
public PhotatoVideo(Path rootFolder, Path path, Metadata metadata, PictureInfos thumbnailInfos, PictureInfos fullScreenInfos, long lastModificationTimestamp) {
    super("video", rootFolder, path, metadata, thumbnailInfos, fullScreenInfos, lastModificationTimestamp);

    if (this.filename.length() > 40 || this.filename.contains("_") || this.filename.toLowerCase().startsWith("vid")) {
        this.name = path.getParent().getFileName().toString();
    } else {
        this.name = path.getParent().getFileName() + "/" + this.filename;
    }

    this.videoType = "video/" + FileHelper.getExtension(path.toString()).toLowerCase();
    this.videoPath = Routes.rawVideosRootUrl + "/" + PathHelper.getPathString(rootFolder, path);

    long tmpFilesize;
    try {
        tmpFilesize =Files.size(this.fsPath);
    } catch (IOException ex) {
       tmpFilesize=0;
    }
    this.filesize = tmpFilesize;
}
 
Example 2
Project: clustercode   File: FileSizeConstraint.java   View Source Code Vote up 6 votes
@Override
public boolean accept(Media candidate) {
    Path file = scanSettings.getBaseInputDir().resolve(candidate.getSourcePath());
    try {
        long size = Files.size(file);
        if (minSize > 0 && maxSize > 0) {
            // file between max and min
            return logAndReturn(size >= minSize && size <= maxSize, file, size);
        } else if (minSize <= 0) {
            // size smaller than max, min disabled
            return logAndReturn(size <= maxSize, file, size);
        } else {
            // size greater than min, max disabled
            return logAndReturn(size >= minSize, file, size);
        }
    } catch (IOException e) {
        log.warn("Could not determine file size of {}: {}. Declined file.", file, e.toString());
        return false;
    }
}
 
Example 3
Project: UDE   File: FileExplorerFx.java   View Source Code Vote up 6 votes
public String calculateSize(File f){
    String s;long sizeInByte=0; Path path;
    if(IsDrive(f)){
        return Long.toString(f.getTotalSpace()/(1024*1024*1024))+"GB";
    }

    path = Paths.get(f.toURI());
    //sizeInByte = f.getTotalSpace(); // terrible idea cz sob subfolder e 199GB, 99GB esob dekhay >_<
    try {
        sizeInByte = Files.size(path);//at least works ^_^
    } catch (IOException e) {
        e.printStackTrace();
    }
    if(sizeInByte<(1024)){s = Long.toString(sizeInByte)+"B"; return s; }
    else if(sizeInByte>=(1024) && sizeInByte<(1024*1024)){ long sizeInKb = sizeInByte/1024; s = Long.toString(sizeInKb)+"KB"; return s; }
    else if(sizeInByte>=(1024*1024) && sizeInByte<(1024*1024*1024)){ long sizeInMb = sizeInByte/(1024*1024); s = Long.toString(sizeInMb)+"MB"; return s; }
    else if(sizeInByte>=(1024*1024*1024)){ long sizeInGb = sizeInByte/(1024*1024*1024); s = Long.toString(sizeInGb)+"GB"; return s; }

    return null;
}
 
Example 4
Project: disq   File: StateFile.java   View Source Code Vote up 6 votes
public StateFile(Path file) throws IOException {
    this.fileCounts = new int[MAX_FILES];
    this.randomWrite = new RandomAccessFile(file.toFile(), "rw");
    if (Files.exists(file) && Files.size(file) == EXPECTED_SIZE) {
        try (DataInputStream stream = new DataInputStream(new FileInputStream(file.toFile()))) {
            readFile = stream.readShort();
            writeFile = stream.readShort();
            readPosition = stream.readInt();
            writePosition = stream.readInt();
            count = stream.readLong();
            bytes = stream.readLong();
            for (int i = 0; i < MAX_FILES; i++)
                fileCounts[i] = stream.readInt();
            unflushed = 0;
        }
    }
}
 
Example 5
Project: Matcher   File: InputFile.java   View Source Code Vote up 5 votes
public boolean equals(Path path) {
	try {
		if (this.path != null) return Files.isSameFile(path, this.path);

		if (!getSanitizedFileName(path).equals(fileName)) return false;
		if (Files.size(path) != size) return false;

		return Arrays.equals(sha256, hash(path));
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example 6
Project: jobson   File: Helpers.java   View Source Code Vote up 5 votes
public static BinaryData streamBinaryData(Path p) {
    try {
        final long size = Files.size(p);
        final InputStream dataStream = Files.newInputStream(p);

        return new BinaryData(dataStream, size);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 7
Project: incubator-netbeans   File: FileObjects.java   View Source Code Vote up 5 votes
@Override
public final CharSequence getCharContent(final boolean ignoreEncodingErrors) throws IOException {
    final long len = Files.size(resolvePath());
    return FileObjects.getCharContent(
            openInputStream(),
            encoding,
            null,
            len,
            ignoreEncodingErrors);
}
 
Example 8
Project: r8   File: R8InliningTest.java   View Source Code Vote up 5 votes
@Test
public void processedFileIsSmaller() throws Throwable {
  long original = Files.size(getOriginalDexFile());
  long generated = Files.size(getGeneratedDexFile());
  final boolean ALWAYS_DUMP = false;  // Used for debugging.
  if (ALWAYS_DUMP || generated > original) {
    dump(getOriginalDexFile(), "Original");
    dump(getGeneratedDexFile(), "Generated");
  }
  assertTrue("Inlining failed to reduce size", original > generated);
}
 
Example 9
Project: JavaRushTasks   File: FileBucket.java   View Source Code Vote up 5 votes
public long getFileSize() {
    try {
        return Files.size(path);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}
 
Example 10
Project: openjdk-jdk10   File: DirArchive.java   View Source Code Vote up 5 votes
FileEntry(Path path, String name) {
    super(DirArchive.this, getPathName(path), name,
          Archive.Entry.EntryType.CLASS_OR_RESOURCE);
    this.path = path;
    try {
        size = Files.size(path);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 11
Project: BIMplatform   File: FileInputStreamDataSource.java   View Source Code Vote up 5 votes
public long size() {
	try {
		return Files.size(file);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return -1;
}
 
Example 12
Project: bach   File: GenerateModuleProperties.java   View Source Code Vote up 5 votes
private boolean scanMetadata(URI uri) {
  var meta = read(uri.resolve("maven-metadata.xml")).orElseThrow(Error::new);
  if (meta.contains("<versioning>")) {
    var updated = substring(meta, "<lastUpdated>", "<");
    if (updated.length() != 14) {
      System.out.println("  [!] unexpected <lastUpdated> format: " + updated);
      return true;
    }
    if (updated.compareTo("20170101000000") < 0) {
      System.out.println("  [!] too old: " + updated);
      return true;
    }
    var group = substring(meta, "<groupId>", "<");
    var artifact = substring(meta, "<artifactId>", "<");
    var version = substring(meta, "<release>", "<"); // TODO Consider 'latest'?
    try {
      // TODO load .pom and assume "jar" packaging
      var jar = load(uri.resolve(version + "/" + artifact + "-" + version + ".jar"));
      if (Files.exists(jar) && Files.size(jar) > 0) {
        scanJar(jar, group, artifact, version);
      }
      Files.deleteIfExists(jar);
    } catch (Exception e) {
      throw new Error("Scanning maven-metadata.xml failed!", e);
    }
    return true;
  }
  return false;
}
 
Example 13
Project: cyberduck   File: LocalAttributes.java   View Source Code Vote up 5 votes
@Override
public long getSize() {
    if(Files.exists(Paths.get(path))) {
        try {
            return Files.size(Paths.get(path));
        }
        catch(IOException e) {
            log.warn(String.format("Failure getting size of %s. %s", path, e.getMessage()));
        }
    }
    return -1;
}
 
Example 14
Project: disq   File: DiskRawQueue.java   View Source Code Vote up 5 votes
private void gc() throws IOException {
    Path file = makeDataPath(state.getReadFile());
    boolean shouldFlush = false;
    while (!Files.exists(file) && !state.sameFileReadWrite()) {
        state.advanceReadFile(0);
        file = makeDataPath(state.getReadFile());
        shouldFlush = true;
    }
    long totalBytes = 0;
    long totalCount = 0;
    for (int i = 0; i < StateFile.MAX_FILES; i++) {
        Path path = makeDataPath(i);
        if (Files.exists(path)) {
            if (!state.isInUse(i)) {
                tryDeleteFile(i, false);
            } else {
                totalBytes += Files.size(path);
                totalCount += state.getFileCount(i);
            }
        }
    }

    shouldFlush |= state.fixCounts(totalCount, totalBytes);

    if (shouldFlush)
        internalFlush();

}
 
Example 15
Project: openjdk-jdk10   File: ZipFileStore.java   View Source Code Vote up 5 votes
public ZipFileStoreAttributes(ZipFileStore fileStore)
    throws IOException
{
    Path path = FileSystems.getDefault().getPath(fileStore.name());
    this.size = Files.size(path);
    this.fstore = Files.getFileStore(path);
}
 
Example 16
Project: openjdk-jdk10   File: ShortRequestBody.java   View Source Code Vote up 4 votes
FileRequestBody(Path path, int additionalLength) throws IOException {
    super(HttpRequest.BodyProcessor.fromFile(path),
          Files.size(path) + additionalLength);
}
 
Example 17
Project: cf-mta-deploy-service   File: FileSplitter.java   View Source Code Vote up 4 votes
public FileSplitter(Path filePath) throws IOException {
    this(filePath.getFileName().toString(), filePath.toAbsolutePath().toString(), Files.newInputStream(filePath), null);
    this.fileSize = Files.size(filePath);
}
 
Example 18
Project: qpp-conversion-tool   File: InputStreamSupplierSourceTest.java   View Source Code Vote up 4 votes
private static InputStreamSupplierSource source(String path) throws IOException {
	return new InputStreamSupplierSource(path, () -> stream(path), Files.size(Paths.get(path)));
}
 
Example 19
Project: mpeg-audio-streams   File: TestIntegrationReadWrite.java   View Source Code Vote up 4 votes
/**
 * assertByteWiseReencodedFile.
 * @param fileName {@link String}
 * @throws IOException
 */
private static void assertByteWiseReencodedFile(final String fileName) throws IOException {
    final File in = new File(fileName);
    // assume there is just one id 3 tag at the very beginning...
    final ID3Tag firstID3Tag = MPEGAudio.decodeFirstID3Tag(in);
    if (TestIntegrationReadWrite.LOG.isInfoEnabled()) {
        TestIntegrationReadWrite.LOG.info("" + firstID3Tag); //$NON-NLS-1$
    }
    final DecodingResult dr = MPEGAudio.decode(in, MPEGAudioContentFilter.MPEG_AUDIO_FRAMES);
    assertEquals(0, dr.getSkippedBits());
    final File out = File.createTempFile("TestIntegrationReadWrite-TEST", ".mp3"); //$NON-NLS-1$ //$NON-NLS-2$
    //        final File out = new File("out.mp3");
    if (TestIntegrationReadWrite.LOG.isInfoEnabled()) {
        TestIntegrationReadWrite.LOG.info("Created tmp file [" + out.getAbsolutePath() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    try (FileOutputStream fos = new FileOutputStream(out)) {
        MPEGAudio.encode(dr.getContent(), fos, true);
    }
    // SEBASTIAN since we do not encode ID3Tags until now, those bytes we have less in our result
    final int id3TagSize = firstID3Tag != null ? firstID3Tag.getOverallSize() : 0;
    final long bytesWithoutID3 = Files.size(in.toPath()) - id3TagSize;
    assertEquals(bytesWithoutID3, Files.size(out.toPath()));

    int byteNum = 0;
    try (FileInputStream inFis = new FileInputStream(in)) {
        try (FileInputStream outFis = new FileInputStream(out)) {
            // forget about the id3 tag bytes
            for (int i = id3TagSize; i > 0; i--) {
                inFis.read();
            }
            for (long i = bytesWithoutID3; i > 0; i--) {
                assertEquals("byteNum: " + byteNum, Integer.toBinaryString(inFis.read()), //$NON-NLS-1$
                        Integer.toBinaryString(outFis.read()));
                byteNum++;
            }
        }
    }

    final DecodingResult drreencoded = MPEGAudio.decode(out, MPEGAudioContentFilter.MPEG_AUDIO_FRAMES);
    final List<MPEGAudioContent> content = dr.getContent();
    final Iterator<MPEGAudioContent> iterator = content.iterator();
    final Iterator<MPEGAudioContent> iterator2 = drreencoded.getContent().iterator();
    while (iterator.hasNext() && iterator2.hasNext()) {
        assertEquals(iterator.next(), iterator2.next());
    }

    Files.deleteIfExists(out.toPath());
}
 
Example 20
Project: odoxSync   File: DirectoryScanner.java   View Source Code Vote up 4 votes
private void processFileFast(File file) {
    try {

        boolean doScan = false;

        Path path = Paths.get(workingDirectory, file.getName());

        if(!Files.exists(path)) {
            return;
        }

        FileTime lastModifiedTime = Files.getLastModifiedTime(path);

        if (lastModifiedTime.compareTo(file.getLastModified()) == 0) {
            logger.fine(" File has not been modified [" + file.getName() + "]");
        } else {
            doScan = true;
        }
        file.setLastModified(lastModifiedTime);

        long size = Files.size(path);
        if (size != file.getSize()) {
            logger.fine("Recalculation regions for [" + file.getName() + "]");
            reCalculateRegions(file);
            doScan = true;
        }

        if (doScan) {
            long startTime = System.currentTimeMillis();
            logger.fine("Starting scan for [" + file.getName() + "]");
            FileScanner fileScanner = new FileScanner(workingDirectory,
                    new FastFileProcessorFactory(new FileRegionHashMapDigestHandler()), activityStaler, false);
            fileScanner.scanFile(file);
            long duration = System.currentTimeMillis() - startTime;
            logger.fine("Finished scan for [" + file.getName() + "] in [" + duration + "ms]");
        }

    } catch (IOException e) {
        logger.log(Level.SEVERE, "Unable to scan file [" + file.getName() + "]", e);
    }
}