Created
April 2, 2014 17:53
-
-
Save dobsondev/9939404 to your computer and use it in GitHub Desktop.
Small Java program that will take in a file full of words seperated into lines and capitalizes those words and sorts them alphabetically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.PrintStream; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
import java.util.Scanner; | |
public class CapitalizeAlphabetical { | |
public static void main(String[] args) { | |
if (args.length == 1) { | |
// Display help message | |
if (args[0].toLowerCase().contains( "help".toLowerCase() )) { | |
System.out.println("USAGE: java CapitalizeAlphabetical <file_to_be_modified>"); | |
} else { | |
File file = new File(args[0]); | |
// Break down the file path | |
String[] fileParts = args[0].split("/"); | |
String fileName = fileParts[fileParts.length - 1]; | |
String filePath = ""; | |
for (int i = 0; i < fileParts.length - 1; i++) { | |
filePath += fileParts[i] + "/"; | |
} | |
try { | |
List<String> words = new ArrayList<String>(); | |
Scanner in = new Scanner(file); | |
// Get words and capitalize them | |
while (in.hasNextLine()) { | |
String word = in.next(); | |
words.add(Character.toUpperCase(word.charAt(0)) + word.substring(1)); | |
} | |
// Sort words alphabetically | |
Collections.sort(words, new Comparator<String>() { | |
@Override | |
public int compare(String o1, String o2) { | |
return o1.compareToIgnoreCase(o2); | |
} | |
}); | |
// Write out the new file | |
PrintStream out = new java.io.PrintStream(filePath+ "sorted-" + fileName); | |
for (int i = 0; i < words.size(); i++) { | |
out.println(words.get(i)); | |
} | |
out.flush(); | |
out.close(); | |
System.out.println("FINISHED. Wrote: " + filePath+ "sorted-" + fileName); | |
} catch (FileNotFoundException e) { e.printStackTrace(); } | |
} | |
} else { | |
System.out.println("USAGE: java CapitalizeAlphabetical <file_to_be_modified>"); | |
} | |
}// END public static void main | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment