Skip to content

Instantly share code, notes, and snippets.

@prestongarno
Created August 21, 2017 19:13
Show Gist options
  • Save prestongarno/b0034ae37ca5e757a35f996b4c72620d to your computer and use it in GitHub Desktop.
Save prestongarno/b0034ae37ca5e757a35f996b4c72620d to your computer and use it in GitHub Desktop.
import java.io.*;
import java.nio.file.*;
import java.nio.file.spi.FileSystemProvider;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.swing.*;
public class CustomFileChooser {
public static void main(String[] args) throws IOException {
Function<String, Integer> countDir = str -> (str.length() - str.replace("/", "").length());
List<String> directories = runCommand("cd ~/Documents && find . -type d ")
.stream()
.map(str -> str.substring(1))
.sorted((o1, o2) -> {
Integer o1Count = countDir.apply(o1);
Integer o2count = countDir.apply(o2);
if (o1Count > o2count) return 1;
else if (o2count > o1Count) return -1;
else return 0;
})
.collect(Collectors.toList());
directories.forEach(System.out::println);
String url = System.getProperty("java.io.tmpdir") + "/javaFileChooser";
System.out.println(url);
File file = new File(url);
Path p = Files.createDirectory(file.toPath());
Runtime.getRuntime().addShutdownHook(new Thread(() -> runCommand("rm -rf " + file.toPath())));
FileSystemProvider.installedProviders().get(0).checkAccess(file.toPath(), AccessMode.WRITE);
directories.forEach(str -> {
try {
Files.createDirectory(new File(file.toPath().toString() + "/" + str).toPath());
} catch (Exception e) {
e.printStackTrace();
}
});
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(file);
fc.setSize(400, 400);
fc.setVisible(true);
fc.setControlButtonsAreShown(true);
int returnVal = fc.showOpenDialog(null);
}
public static List<String> runCommand(String command) {
try (InputStream inputStream = Runtime.getRuntime()
.exec(new String[]{"sh", "-c", command}).getInputStream();
Reader in = new InputStreamReader(inputStream)) {
return new BufferedReader(in).lines().collect(Collectors.toList());
} catch (IOException e) {
return Collections.emptyList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment