Search code examples
javaoutputprintwriter

PrintWriter does not write to specified file


I have a program that has to read in a file calculate multiple things such as how many vowels in the file etc. For testing purposes I have just been printing the results to the console however I need it to be printed to a separate file so I am using Print Writer. I will include my whole code, so you can see exactly what it is doing.

   //Variables
    int vowels = 0, digits = 0, spaces = 0, upperCase = 0, lowerCase = 0;
    char ch;

    // Creates File Chooser and Scans Selected file.
    Scanner in = null;
    File selectedFile = null;
    JFileChooser chooser = new JFileChooser("E:/OOSD/src/textAnalyser");
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile();
        in = new Scanner(selectedFile);
    }

    //Loops through the file until it has counted everything. 
    while (in.hasNext()) {
        //Gets the next line from the input
        String line = in.nextLine();
        // loop goes on till it has no next line.
        for (int i = 0; i < line.length(); i++) {   
            ch = line.charAt(i);
    if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i'
    || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') {
                vowels++;
            } else if (Character.isDigit(ch)) {
                digits++;
            } else if (Character.isWhitespace(ch)) {
                spaces++;
            } else if (Character.isUpperCase(ch)) {
                upperCase++;
            } else if (Character.isLowerCase(ch)) {
                lowerCase++;
            }
        }
    }//Ends While Loop.

    PrintWriter writer = new PrintWriter("Output.txt", "UTF-8");
    writer.println("Vowels: " + vowels);
    writer.println("Digits : " + digits);
    writer.println("Spaces : " + spaces);
    writer.println("Capital Letters : " + upperCase);
    writer.println("LoweCase : " + lowerCase);
    writer.close();

If you could tell me why it won't print to the output file specified that would be great thanks :) sorry that it is a pretty long question.


Solution

  • for your program to work you need to flush your PrintWriter before closing it.

        PrintWriter writer = new PrintWriter("C:/Users/r7h8/Output.txt", "UTF-8");
        writer.println("Vowels: " + vowels);
        writer.println("Digits : " + digits);
        writer.println("Spaces : " + spaces);
        writer.println("Capital Letters : " + upperCase);
        writer.println("LoweCase : " + lowerCase);
        writer.flush();
        writer.close();
    

    When you flush it, the content is written to the file.

    Best regards.