我正在尝试在名为 doctor.txt
的文件中打印“测试”或其他内容。
每当我运行该程序时,文件中的内容都是空白。另外,您是否必须事先在文件夹中制作.txt,还是它会自动为您制作该文件?
这是我的代码:
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());
}
}
最佳答案
将doctor.close();
放在doctor.write("test");
之后。
关于java - FileWriter 不写入 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515792/