Uppercase File Converter

The problem

Write a program that asks the user for the names of two files. The first file should be opened for reading and the second file should be opened for writing. The program should read the contents of the first file, change all characters to uppercase, and store the results in the second files. The second file will be a copy of the first file, except that all the characters will be uppercase. Use Notepad or another text editor to create a simple file that can be used to test the program.

Note: There are many utility classes that handle file i/o. In this exercise we will demonstrate mechanism introduced in java 7 with new file IO api. In addition, we will use java 8 stream intermediate operation to call String.toUpperCase. In the event you are not using java 8 you could create a method that accepts a List and call the toUpperCase on each element.

Breaking it down

public static void main(String[] args) throws IOException,
            URISyntaxException {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Ask user for file name
    System.out.print("Enter the input file name: ");
    String fileToRead = keyboard.nextLine();

    // Ask user for output file name
    System.out.print("Enter the output file name: ");
    String outputFileName = keyboard.nextLine();

    // Find the path of file in class path
    String fileLocation = getFileLocation(fileToRead);

    // read all lines into file
    Path inputPath = Paths.get(fileLocation);
    List<String> fileLines = java.nio.file.Files.readAllLines(inputPath);

    // iterate each line in file calling toUpperCase
    // using java 8 streams
    List<String> linesToUpperCase = fileLines.stream()
            .map(s -> s.toUpperCase()).collect(Collectors.toList());

    // write to file
    Path outputPath = Paths.get(outputFileName);
    java.nio.file.Files.write(outputPath, linesToUpperCase,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE);

    keyboard.close();
}

/**
 * Method will just return the location of the file in the class path
 * 
 * @param fileName
 * @return
 */
static String getFileLocation(String fileName) {
    return UppercaseFileConverter.class.getResource(fileName).getPath();
}

File input/output

Input

Welcome to Level up lunch, come explore java tutorials, exercises and examples.

Output

WELCOME TO LEVEL UP LUNCH, COME EXPLORE JAVA TUTORIALS, EXERCISES AND EXAMPLES.

Level Up

  • Modify the program to only capitalize the first letter of each word
  • Instead of using java 7 files, try using guava or apache commons file utility