java.nio.file.AccessMode#java.nio.file.FileStore源码实例Demo

下面列出了java.nio.file.AccessMode#java.nio.file.FileStore 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Quelea   文件: AddDVDActionHandler.java
/**
 * Get the location of the DVD, or null if no DVD can be found.
 * <p>
 * @return the DVD location.
 */
private String getLocation() {
    FileSystem fs = FileSystems.getDefault();
    for(Path rootPath : fs.getRootDirectories()) {
        try {
            FileStore store = Files.getFileStore(rootPath);
            if(store.type().toLowerCase().contains("udf")) {
                if(store.getTotalSpace()>10000000000L) { //Blu-ray
                    return "bluray:///" + rootPath.toString();
                }
                else {
                    return "dvdsimple:///" + rootPath.toString(); //DVD
                }
            }
        }
        catch(IOException ex) {
            //Never mind
        }
    }
    return null;
}
 
源代码2 项目: jsr203-hadoop   文件: TestFileStore.java
@Test
public void testFileStore() throws URISyntaxException, IOException {
  URI uri = clusterUri.resolve("/tmp/testFileStore");
  Path path = Paths.get(uri);
  if (Files.exists(path))
    Files.delete(path);
  assertFalse(Files.exists(path));
  Files.createFile(path);
  assertTrue(Files.exists(path));
  FileStore st = Files.getFileStore(path);
  assertNotNull(st);
  Assert.assertNotNull(st.name());
  Assert.assertNotNull(st.type());

  Assert.assertFalse(st.isReadOnly());

  Assert.assertNotEquals(0, st.getTotalSpace());
  Assert.assertNotEquals(0, st.getUnallocatedSpace());
  Assert.assertNotEquals(0, st.getUsableSpace());

  Assert
      .assertTrue(st.supportsFileAttributeView(BasicFileAttributeView.class));
  Assert.assertTrue(st.supportsFileAttributeView("basic"));

  st.getAttribute("test");
}
 
源代码3 项目: nexus-public   文件: FileBlobStore.java
@Override
public boolean isStorageAvailable() {
  try {
    FileStore fileStore = Files.getFileStore(contentDir);
    long usableSpace = fileStore.getUsableSpace();
    boolean readOnly = fileStore.isReadOnly();
    boolean result = !readOnly && usableSpace > 0;
    if (!result) {
      log.warn("File blob store '{}' is not writable. Read only: {}. Usable space: {}",
          getBlobStoreConfiguration().getName(), readOnly, usableSpace);
    }
    return result;
  }
  catch (IOException e) {
    log.warn("File blob store '{}' is not writable.", getBlobStoreConfiguration().getName(), e);
    return false;
  }
}
 
源代码4 项目: packagedrone   文件: InformationController.java
private void fillFromStorage ( final Map<String, Object> model )
{
    if ( this.manager != null )
    {
        final Path base = this.manager.getContext ().getBasePath ();
        try
        {
            final FileStore store = Files.getFileStore ( base );
            model.put ( "storageTotal", store.getTotalSpace () );
            model.put ( "storageFree", store.getUsableSpace () );
            model.put ( "storageUsed", store.getTotalSpace () - store.getUsableSpace () );
            model.put ( "storageName", store.name () );
        }
        catch ( final Exception e )
        {
            logger.warn ( "Failed to check storage space", e );
            // ignore
        }
    }
}
 
源代码5 项目: mycore   文件: MCRIFSFileSystem.java
@Override
public Iterable<FileStore> getFileStores() {
    return MCRStoreCenter.instance().getCurrentStores(org.mycore.datamodel.ifs2.MCRFileStore.class)
        .filter(s -> s.getID().startsWith(MCRFileSystemUtils.STORE_ID_PREFIX))
        .sorted(Comparator.comparing(MCRStore::getID))
        .map(MCRStore::getID)
        .distinct()
        .map(storeId -> {
            try {
                return MCRFileStore.getInstance(storeId);
            } catch (IOException e) {
                LogManager.getLogger().error("Error while iterating FileStores.", e);
                return null;
            }
        })
        .filter(Objects::nonNull)
        .map(FileStore.class::cast)::iterator;
}
 
源代码6 项目: lucene-solr   文件: FilterFileSystem.java
@Override
public Iterable<FileStore> getFileStores() {
  final Iterable<FileStore> fileStores = delegate.getFileStores();
  return () -> {
    final Iterator<FileStore> iterator = fileStores.iterator();
    return new Iterator<FileStore>() {
      @Override
      public boolean hasNext() {
        return iterator.hasNext();
      }

      @Override
      public FileStore next() {
        return new FilterFileStore(iterator.next(), parent.getScheme()) {};
      }
      
      @Override
      public void remove() {
        iterator.remove();
      }
    };
  };
}
 
源代码7 项目: lucene-solr   文件: TestIOUtils.java
public MockLinuxFileSystemProvider(FileSystem delegateInstance, final Map<String,FileStore> filesToStore, Path root) {
  super("mocklinux://", delegateInstance);
  if (mockedPath(root)) {
    throw new AssumptionViolatedException("can't mock /sys and /dev inside of /sys or /dev!");
  }
  final Collection<FileStore> allStores = new HashSet<>(filesToStore.values());
  this.fileSystem = new FilterFileSystem(this, delegateInstance) {
    @Override
    public Iterable<FileStore> getFileStores() {
      return allStores;
    }

    @Override
    public Path getPath(String first, String... more) {
      return new MockLinuxPath(delegateInstance.getPath(first, more), this);
    }
  };
  this.filesToStore = filesToStore;
  this.root = new MockLinuxPath(root, this.fileSystem);
}
 
源代码8 项目: lucene-solr   文件: TestIOUtils.java
public void testSSD() throws Exception {
  assumeFalse("windows is not supported", Constants.WINDOWS);
  Path dir = createTempDir();
  dir = FilterPath.unwrap(dir).toRealPath();
  
  // fake ssd
  FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz1)", "btrfs", "/dev/zzz1");
  // make a fake /dev/zzz1 for it
  Path devdir = dir.resolve("dev");
  Files.createDirectories(devdir);
  Files.createFile(devdir.resolve("zzz1"));
  // make a fake /sys/block/zzz/queue/rotational file for it
  Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
  Files.createDirectories(sysdir);
  try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
    o.write("0\n".getBytes(StandardCharsets.US_ASCII));
  }
  Map<String,FileStore> mappings = Collections.singletonMap(dir.toString(), root);
  FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
  
  Path mockPath = mockLinux.getPath(dir.toString());
  assertFalse(IOUtils.spinsLinux(mockPath));
}
 
源代码9 项目: lucene-solr   文件: TestIOUtils.java
public void testManyPartitions() throws Exception {
  assumeFalse("windows is not supported", Constants.WINDOWS);
  Path dir = createTempDir();
  dir = FilterPath.unwrap(dir).toRealPath();
  
  // fake ssd
  FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz12)", "zfs", "/dev/zzz12");
  // make a fake /dev/zzz11 for it
  Path devdir = dir.resolve("dev");
  Files.createDirectories(devdir);
  Files.createFile(devdir.resolve("zzz12"));
  // make a fake /sys/block/zzz/queue/rotational file for it
  Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
  Files.createDirectories(sysdir);
  try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
    o.write("0\n".getBytes(StandardCharsets.US_ASCII));
  }
  Map<String,FileStore> mappings = Collections.singletonMap(dir.toString(), root);
  FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
  
  Path mockPath = mockLinux.getPath(dir.toString());
  assertFalse(IOUtils.spinsLinux(mockPath));
}
 
源代码10 项目: presto   文件: FileSingleStreamSpillerFactory.java
private boolean hasEnoughDiskSpace(Path path)
{
    try {
        FileStore fileStore = getFileStore(path);
        return fileStore.getUsableSpace() > fileStore.getTotalSpace() * (1.0 - maxUsedSpaceThreshold);
    }
    catch (IOException e) {
        throw new PrestoException(OUT_OF_SPILL_SPACE, "Cannot determine free space for spill", e);
    }
}
 
源代码11 项目: boon   文件: BatchFileWriter.java
public void diagnose() {

        Objects.requireNonNull(fileName(), "the filename should not be null, " +
                "you have misconfigured this service, fatal error");

        final Path path =
                IO.path(fileName());

        puts("in diagnose");

        puts("Filename           :", path.toAbsolutePath());
        puts("File exists?       :", Files.exists(path));
        puts("File writeable?    :", Files.isWritable(path));


        puts("Output dir                :", outputDir.toAbsolutePath());
        puts("Output dir  exists?       :", Files.exists(outputDir));
        puts("Output dir  writeable?    :", Files.isWritable(outputDir));

        if (!Files.isWritable(outputDir) || !Files.exists(outputDir)) {
            error.set(true);
        }

        try {
            FileStore fileStore = Files.getFileStore(path.getParent());
            puts("Total space           :", str(fileStore.getTotalSpace()));
            puts("Use-able space        :", str(fileStore.getUsableSpace()));
            puts("Free Space            :", str(fileStore.getUnallocatedSpace()));
            puts("type                  :", fileStore.type());
            puts("name                  :", fileStore.name());
            puts("read-only             :", fileStore.isReadOnly());

        } catch (IOException e) {

            e.printStackTrace();
        }
    }
 
源代码12 项目: dragonwell8_jdk   文件: FaultyFileSystem.java
@Override
public Iterable<FileStore> getFileStores() {
    FileStore store;
    try {
        store = Files.getFileStore(root);
    } catch (IOException ioe) {
        store = null;
    }
    return SoleIterable(store);
}
 
源代码13 项目: openjdk-8   文件: FaultyFileSystem.java
@Override
public Iterable<FileStore> getFileStores() {
    FileStore store;
    try {
        store = Files.getFileStore(root);
    } catch (IOException ioe) {
        store = null;
    }
    return SoleIterable(store);
}
 
源代码14 项目: jdk8u60   文件: FaultyFileSystem.java
@Override
public Iterable<FileStore> getFileStores() {
    FileStore store;
    try {
        store = Files.getFileStore(root);
    } catch (IOException ioe) {
        store = null;
    }
    return SoleIterable(store);
}
 
源代码15 项目: nyzoVerifier   文件: ConsensusTracker.java
private static long getUsableSpace() {

        // Ensure that the directory exists.
        rootDirectory.mkdirs();

        // Get the usable space.
        long freeSpace = 0L;
        Path path = Paths.get(rootDirectory.getAbsolutePath());
        try {
            FileStore store = Files.getFileStore(path);
            freeSpace = store.getUsableSpace();
        } catch (Exception ignored) { }

        return freeSpace;
    }
 
源代码16 项目: datacollector   文件: RuntimeInfo.java
private String sizeOfDir(String directory) {
  try {
    Path path = Paths.get(directory);
    FileStore store = Files.getFileStore(path.getRoot());
    return Utils.format("(total {}, unallocated {}, root {})", FileUtils.byteCountToDisplaySize(store.getTotalSpace()), FileUtils.byteCountToDisplaySize(store.getUnallocatedSpace()), path.getRoot());
  } catch (Exception e) {
    return "";
  }
}
 
源代码17 项目: ParallelGit   文件: GitFileSystemBasicTest.java
@Test
public void getFileStores_shouldContainTheOnlyFileStore() {
  Collection<FileStore> stores = new ArrayList<>();
  for(FileStore root : gfs.getFileStores())
    stores.add(root);
  assertTrue(stores.contains(gfs.getFileStore()));
}
 
源代码18 项目: crate   文件: ESFileStore.java
@SuppressForbidden(reason = "tries to determine if disk is spinning")
// TODO: move PathUtils to be package-private here instead of
// public+forbidden api!
ESFileStore(final FileStore in) {
    this.in = in;
    if (Constants.LINUX) {
        try {
            final List<String> lines = Files.readAllLines(PathUtils.get("/proc/self/mountinfo"));
            for (final String line : lines) {
                final String[] fields = line.trim().split("\\s+");
                final String mountPoint = fields[4];
                if (mountPoint.equals(getMountPointLinux(in))) {
                    final String[] deviceNumbers = fields[2].split(":");
                    majorDeviceNumber = Integer.parseInt(deviceNumbers[0]);
                    minorDeviceNumber = Integer.parseInt(deviceNumbers[1]);
                    break;
                }
            }
        } catch (final Exception e) {
            majorDeviceNumber = -1;
            minorDeviceNumber = -1;
        }
    } else {
        majorDeviceNumber = -1;
        minorDeviceNumber = -1;
    }
}
 
源代码19 项目: swage   文件: DiskUsageSensor.java
@Override
public void sense(final MetricContext metricContext) throws SenseException
{
    try {
        // Determine the file store for the directory the JVM was started in
        FileStore fileStore = Files.getFileStore(Paths.get(System.getProperty("user.dir")));

        long total = fileStore.getTotalSpace();
        long free = fileStore.getUsableSpace();
        double percent_free = 100.0 * ((double)(total-free)/(double)total);
        metricContext.record(DISK_USED, percent_free, Unit.PERCENT);
    } catch (IOException e) {
        throw new SenseException("Problem reading disk space", e);
    }
}
 
protected BundleFileStore(BundleFileSystem fs, FileStore origFileStore) {
	if (fs == null || origFileStore == null) {
		throw new NullPointerException();
	}
	// this.fs = fs;
	this.origFileStore = origFileStore;
}
 
源代码21 项目: LagMonitor   文件: NativeManager.java
public long getFreeSpace() {
    long freeSpace = 0;
    try {
        FileStore fileStore = Files.getFileStore(Paths.get("."));
        freeSpace = fileStore.getUsableSpace();
    } catch (IOException ioEx) {
        logger.log(Level.WARNING, "Cannot calculate free/total disk space", ioEx);
    }

    return freeSpace;
}
 
源代码22 项目: jdk8u_jdk   文件: Basic.java
static void checkFileStores(FileSystem fs) throws IOException {
    // sanity check method
    if (FileUtils.areFileSystemsAccessible()) {
        System.out.println("\n--- Begin FileStores ---");
        for (FileStore store: fs.getFileStores()) {
            System.out.println(store);
        }
        System.out.println("--- EndFileStores ---\n");
    } else {
        System.err.println
            ("Skipping FileStore check due to file system access failure");
    }
}
 
源代码23 项目: LagMonitor   文件: NativeManager.java
public long getTotalSpace() {
    long totalSpace = 0;
    try {
        FileStore fileStore = Files.getFileStore(Paths.get("."));
        totalSpace = fileStore.getTotalSpace();
    } catch (IOException ioEx) {
        logger.log(Level.WARNING, "Cannot calculate free disk space", ioEx);
    }

    return totalSpace;
}
 
源代码24 项目: nexus-public   文件: FileBlobStoreMetricsStore.java
@Override
protected AccumulatingBlobStoreMetrics getAccumulatingBlobStoreMetrics() throws BlobStoreMetricsNotAvailableException {
  try {
    FileStore fileStore = Files.getFileStore(storageDirectory);
    ImmutableMap<String, Long> availableSpace = ImmutableMap
        .of("fileStore:" + fileStore.name(), fileStore.getUsableSpace());
    return new AccumulatingBlobStoreMetrics(0, 0, availableSpace, false);
  }
  catch (IOException e) {
    throw new BlobStoreMetricsNotAvailableException(e);
  }
}
 
源代码25 项目: openjdk-jdk9   文件: Basic.java
static void checkFileStores(FileSystem fs) throws IOException {
    // sanity check method
    if (FileUtils.areFileSystemsAccessible()) {
        System.out.println("\n--- Begin FileStores ---");
        for (FileStore store: fs.getFileStores()) {
            System.out.println(store);
        }
        System.out.println("--- EndFileStores ---\n");
    } else {
        System.err.println
            ("Skipping FileStore check due to file system access failure");
    }
}
 
源代码26 项目: spliceengine   文件: FileSystemConfiguration.java
public long freeDiskBytes() throws IOException {
    Iterable<FileStore> fileStores = localFileSystem.getFileStores();
    long totalUsableSpace = 0l;
    for(FileStore fs:fileStores){
        totalUsableSpace+=fs.getUsableSpace();
    }
    return totalUsableSpace;
}
 
源代码27 项目: simple-nfs   文件: LocalFileSystem.java
@Override
public FsStat getFsStat() throws IOException {
    FileStore store = Files.getFileStore(_root);
    long total = store.getTotalSpace();
    long free = store.getUsableSpace();
    return new FsStat(total, Long.MAX_VALUE, total-free, pathToInode.size());
}
 
源代码28 项目: che   文件: FileStoresMeterBinder.java
@Override
public void bindTo(MeterRegistry registry) {
  for (FileStore fileStore : FileSystems.getDefault().getFileStores()) {
    LOG.debug(
        "Add gauge metric for {}, isReadOnly {}, type {}",
        fileStore.name(),
        fileStore.isReadOnly(),
        fileStore.type());
    Iterable<Tag> tagsWithPath = Tags.concat(Tags.empty(), "path", fileStore.toString());

    Gauge.builder("disk.free", fileStore, exceptionToNonWrapper(FileStore::getUnallocatedSpace))
        .tags(tagsWithPath)
        .description("Unallocated space for file storage")
        .baseUnit("bytes")
        .strongReference(true)
        .register(registry);
    Gauge.builder("disk.total", fileStore, exceptionToNonWrapper(FileStore::getTotalSpace))
        .tags(tagsWithPath)
        .description("Total space for file storage")
        .baseUnit("bytes")
        .strongReference(true)
        .register(registry);
    Gauge.builder("disk.usable", fileStore, exceptionToNonWrapper(FileStore::getUsableSpace))
        .tags(tagsWithPath)
        .description("Usable space for file storage")
        .baseUnit("bytes")
        .strongReference(true)
        .register(registry);
  }
}
 
源代码29 项目: bazel-buildfarm   文件: EvenMoreFiles.java
public static boolean isReadOnlyExecutable(Path path) throws IOException {
  FileStore fileStore = Files.getFileStore(path);
  if (fileStore.supportsFileAttributeView("posix")) {
    Set<PosixFilePermission> perms = Files.getPosixFilePermissions(path);
    if (perms.contains(PosixFilePermission.OWNER_EXECUTE)
        && !perms.contains(PosixFilePermission.GROUP_EXECUTE)
        && !perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
      setReadOnlyPerms(path, true);
    }
    return perms.contains(PosixFilePermission.OWNER_EXECUTE);
  } else {
    return Files.isExecutable(path);
  }
}
 
源代码30 项目: jsr203-hadoop   文件: TestFileSystem.java
@Test
public void testFileStore() throws URISyntaxException, IOException {
  URI uri = clusterUri.resolve("/tmp/testFileStore");
  Path path = Paths.get(uri);
  if (Files.exists(path))
    Files.delete(path);
  assertFalse(Files.exists(path));
  Files.createFile(path);
  assertTrue(Files.exists(path));
  FileStore st = Files.getFileStore(path);
  assertNotNull(st);
}