Question: Hello, this program is supposed to take a file/directory name and both print the name, size, path/ absolute path, and last modified date. Then it
Hello, this program is supposed to take a file/directory name and both print the name, size, path/ absolute path, and last modified date. Then it should both print out the info and store it in an output file. It doesn't quite work right though and I wondering if you could correct it.
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.util.LinkedList; import java.util.List; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.DirectoryStream; import java.util.Scanner; public class Directory { /* public static List addFiles(List files, File dir) { if (!Files.isDirectory(dir.toPath())) { files.add(dir); return files; } for (File file : dir.listFiles()) addFiles(files, file); return files; }*/ public static void main(String[] args) throws IOException { Scanner insert = new Scanner(System.in); System.out.println("Enter the directory Name: "); String dirName = insert.next(); Path path = Paths.get(insert.nextLine()); if(Files.exists(path)) { System.out.printf("%n%s exists %n", path.getFileName()); System.out.printf("%s a directory%n", Files.isDirectory(path) ? "Is" : "Isn't"); System.out.printf("%s an absolute path%n", path.isAbsolute() ? "Is":"Isn't"); System.out.printf("Last modified date: %s%n", Files.getLastModifiedTime(path)); // System.out.printf("Size: %s%n", File.size(path)); System.out.printf("Path: %s%n", path); System.out.printf("Absolute path: %s%n", path.toAbsolutePath()); if (Files.isDirectory(path)) { System.out.printf("%nDirectory contents:%n"); DirectoryStream directoryStream = Files.newDirectoryStream(path); for (Path p: directoryStream) System.out.println(p); } } else { System.out.printf("%s doesn't exist, sorry%n", path); } /* PrintWriter writer = new PrintWriter(new FileWriter("output.txt")); List files = addFiles(new LinkedList<>(), new File(dirName)); writer.append(String.format(" File Name File Path File Size Last Modified ")); for (File f : files) { writer.append(String.format("%-20s%-30s%20d bytes ", f.getName(), f.getAbsolutePath(), f.length())); } System.out.println("Result written to " + System.getProperty("user.dir") + File.separator + "output.txt"); insert.close(); writer.close();*/ } }