import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileSizeExample { public static void main(String[] args) { Path path = Paths.get("C:/somefile.txt"); try { long size = Files.size(path); System.out.println("Size of " + path + " is " + size + " bytes."); } catch (IOException e) { System.err.println("Failed to get size of " + path + ": " + e.getMessage()); } } }
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class DirectorySizeExample { public static void main(String[] args) { Path path = Paths.get("C:/somedir"); try { long size = Files.walk(path) .filter(Files::isRegularFile) .mapToLong(p -> { try { return Files.size(p); } catch (IOException e) { return 0L; } }) .sum(); System.out.println("Size of " + path + " and its contents is " + size + " bytes."); } catch (IOException e) { System.err.println("Failed to get size of " + path + " and its contents: " + e.getMessage()); } } }This example uses the `Files.walk()` method to traverse all the files in a directory tree and calculate their total size. It filters out any directories and only includes regular files. If there are any files that cannot be read (due to permission issues or other reasons), their size is considered to be zero. The `mapToLong()` method is used to convert the file sizes to long values, which can then be summed up to obtain the total directory size. Both of these examples use the `java.nio.file` package for working with files and directories.