Skip to content

Instantly share code, notes, and snippets.

@atomAltera
Last active January 3, 2016 13:39
Show Gist options
  • Save atomAltera/8470600 to your computer and use it in GitHub Desktop.
Save atomAltera/8470600 to your computer and use it in GitHub Desktop.
Simple cmd tool to extract and displat file attrs
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.*;
public class T_FileAttrs {
public static void print_usage() {
System.err.println("Usage: java Javast [-s] <path to file> [<path to file> ...]");
System.exit(1);
}
public static void main(String[] args) {
boolean follow_sym = false;
Path[] file_paths;
switch (args.length) {
case 0:
print_usage();
return;
case 1:
file_paths = new Path[]{Paths.get(args[0]),};
break;
default:
follow_sym = args[0].equals("-s");
file_paths = new Path[args.length - 1];
for (int i = 1; i < args.length; i++) {
file_paths[i - 1] = Paths.get(args[i]);
}
}
if (file_paths.length > 1) {
for (Path file_path : file_paths) {
System.out.printf(">>> File info for \"%s\"\n", file_path);
print_file_info(file_path, follow_sym);
System.out.println("------------------\n");
}
} else {
print_file_info(file_paths[0], follow_sym);
}
}
private static void print_file_info(Path file_path, boolean follow_sym) {
LinkOption link_options = follow_sym ? null : LinkOption.NOFOLLOW_LINKS;
if (!Files.exists(file_path)) {
System.out.println("(File not found)");
return;
}
PosixFileAttributes attrs = null;
try {
attrs = Files.readAttributes(file_path, PosixFileAttributes.class, link_options);
} catch (IOException e) {
e.printStackTrace();
}
if (attrs.isRegularFile()) System.out.printf("Is Regular File\n");
if (attrs.isDirectory()) System.out.printf("Is Directory File\n");
if (attrs.isSymbolicLink()) System.out.printf("Is Symbolic Link\n");
if (attrs.isOther()) System.out.printf("Is Other\n");
long size = attrs.size();
double k_size = size / 1024D;
double m_size = k_size / 1024D;
double g_size = m_size / 1024D;
System.out.printf("Size: %d Bytes (%f KB; %f MB; %f GB)\n", size, k_size, m_size, g_size);
System.out.printf("Creation Time: %s\n", attrs.creationTime());
System.out.printf("Last Access Time: %s\n", attrs.lastAccessTime());
System.out.printf("Last Modifed Time: %s\n", attrs.lastModifiedTime());
UserPrincipal user = attrs.owner();
GroupPrincipal group = attrs.group();
System.out.printf("Owner: %s/%s\n", group.getName(), user.getName());
System.out.printf("Permissions: %s\n", PosixFilePermissions.toString(attrs.permissions()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment