Peter Penzov
Peter Penzov

Reputation: 1680

Return null when file is missing or empty

I'm using this code to get some HDD data from Linux:

public void getHDDInfo() throws IOException
    {
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("/sys/block"), "sd*"))
        {
            // Get HDD Model
            StreamSupport.stream(ds.spliterator(), false)
                .map(p -> p.resolve("device/model")).flatMap(wrap(Files::lines))

        }
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("/sys/block"), "sd*"))
        {
            // Get HDD Vendor
            StreamSupport.stream(ds.spliterator(), false)
                .map(p -> p.resolve("device/vendor")).flatMap(wrap(Files::lines))

        }
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("/sys/block"), "sd*"))
        {
            // Get HDD State
            StreamSupport.stream(ds.spliterator(), false)
                .map(p -> p.resolve("device/state")).flatMap(wrap(Files::lines))
                .forEach(System.out::println);
        }
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("/sys/block"), "sd*"))
        {
            // Get HDD Revision
            StreamSupport.stream(ds.spliterator(), false)
                .map(p -> p.resolve("device/rev")).flatMap(wrap(Files::lines))
                .forEach(System.out::println);
        }
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("/sys/block"), "sd*"))
        {
            // Get HDD SCSI Level
            StreamSupport.stream(ds.spliterator(), false)
                .map(p -> p.resolve("device/scsi_level")).flatMap(wrap(Files::lines))
                .forEach(System.out::println);
        }
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("/sys/block"), "sd*"))
        {
            // Get HDD SCSI is removable
            StreamSupport.stream(ds.spliterator(), false)
                .map(p -> p.resolve("device/removable")).flatMap(wrap(Files::lines))
                .forEach(System.out::println);
        }
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("/sys/block"), "sd*"))
        {
            // Get HDD SCSI Level
            StreamSupport.stream(ds.spliterator(), false)
                .map(p -> p.resolve("device/size")).flatMap(wrap(Files::lines))
                .forEach(System.out::println);
        }
    }

But sometimes not all files are available or some of them are empty. Then I get this exception:

java.nio.file.NoSuchFileException: \sys\block

I there a way to modify the code to return null when there is no such file or the file is empty?

Upvotes: 2

Views: 1839

Answers (1)

Drux
Drux

Reputation: 12670

This should handle the cases where files don't exist:

try {
  // most of your stuff
}
catch (NoSuchFileException ex) {
  return null;
}

Upvotes: 5

Related Questions