I have written a simple program in Java 7 to write the .gitignore
of different file types:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class Oye {
private static final String HELP_TXT = "help.txt";
private static final String DATA = "gitignore";
private HashMap<String, String> map = new HashMap<String, String>();
public Oye() {
// Eager approach, building the map in the constructor. Is it good?
File file = new File(DATA);
if (file.exists()) {
if (file.isDirectory()) {
findFiles(file.listFiles());
}
} else {
println("No data folder: " + DATA);
}
}
public static void main(String[] args) {
if (args.length == 0) {
printFile(HELP_TXT);
return;
}
Oye oye = new Oye();
if (args[0].equals("ls")) {
oye.listFiles();
} else {
printFile(oye.getFilePath(args[0]));
}
}
public void findFiles(File[] files) {
for (File file: files) {
if (file.isDirectory()) {
findFiles(file.listFiles());
} else {
String fileName = file.getName();
if (fileName.endsWith(".gitignore")) {
fileName = fileName.substring(0, fileName.indexOf(".gitignore"));
map.put(fileName, file.getAbsolutePath());
}
}
}
}
private String getFilePath(String name) {
if (map.containsKey(name)) {
return map.get(name);
} else {
throw new IllegalArgumentException("No such file: " + name);
}
}
private static void printFile(String path) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(path));
String line;
while (scanner.hasNextLine()) {
println(scanner.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
private static void println(String txt) {
System.out.println(txt);
}
private void listFiles() {
for (String key: map.keySet()) {
println(key);
}
}
}
I know that this code is written in a very naive manner, but I want to know how I can improve my code, specifically about better design decisions and better error handling (should I have my own error classes?).
Assumptions:
- Any single
.gitignore
file can't be more than few hundred lines. .gitignore
directory contains all the content and isn't deeply nested.