Given that you already have code to displaying metadata for a single file, it's trivial to modify it to support multiple files.
All you need is the isDirectory()
and listFiles()
methods of File
(or, if you are on Java 8+, you can use the Files.list(Path)
method, for lazy iteration*).
If your input file is a directory, list each file and recurse:
public class Metadata {
public static void main(String[] args) {
Metadata meta = new Metadata();
File file = new File(args[0]);
if (file.exists()) {
System.out.println("Can find " + file);
meta.readAndDisplayMetadata(file);
}
else {
System.out.println("cannot find file: " + file);
}
}
void readAndDisplayMetadata(File file) {
// If you *don't* want recursive behavior,
// move this block "outside" or to a separate method
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
readAndDisplayMetadata(f);
}
}
// Rest of method as is...
}
}
*) The below is better, if you can use it, as the above can run out of memory if you have many files in the directory.
void readAndDisplayMetadata(File file) throws IOException {
Path path = file.toPath();
if (Files.isDirectory(path /* optional, handle symbolic links */)) {
Files.list(path)
.forEach(p -> readAndDisplayMetadata(p.toFile()));
}
// Rest of method as is...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…