简体   繁体   中英

FileWriter not writing to .txt file

I'm trying to get the "test" or whatever to be printed out inside a file called doctor.txt .

Whenever I run the program, it just comes out to be blank on the file. Also, do you have to make the .txt in the folder beforehand, or does it automatically make the file for you?

Here's my code:

import java.util.Scanner; 
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;

public class Vowels {

    public static void main(String [] args) {
        try {
            int countA = 0;
            int countE = 0;
            int countI = 0;
            int countO = 0;
            int countU = 0;

        Scanner in = new Scanner(new File("poetry.txt"));
        String poetry = "";

        while(in.hasNext()){
            poetry = in.nextLine();
            poetry = poetry.replaceAll(" ", "~");
            System.out.println(poetry);

            for(int v = 0; v < poetry.length(); v++) {
                if(poetry.charAt(v) == 'a') {
                    countA++;
                }
                if(poetry.charAt(v) == 'e') {
                    countE++;
                }
                if(poetry.charAt(v) == 'i') {
                    countI++;
                }
                if(poetry.charAt(v) == 'o') {
                    countO++;
                }
                if(poetry.charAt(v) == 'u') {
                    countU++;
                }
            }

        }
        System.out.println();
        System.out.println("The number of 'A's is: " + countA);
        System.out.println("The number of 'E's is: " + countE);
        System.out.println("The number of 'I's is: " + countI);
        System.out.println("The number of 'O's is: " + countO);
        System.out.println("The number of 'U's is: " + countU);
        FileWriter doctor = new FileWriter("doctor.txt");
        doctor.write("test");
    }
    catch(IOException i) {
        System.out.println("Error: " + i.getMessage());
    }
}

Put doctor.close(); after doctor.write("test"); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM