所以,我试图创建这个应用程序,但仍然在开始,但每次我运行它并尝试在Dictionary.txt文件中写入时,该文件将完全为空。它可以用于我已经制作的另一件事,但在这里它运行良好,终止,当我打开文件时,它是空白的,不成文的。目前在Eclipse Mars上,它没有给我任何错误(除了没有使用随机对象,但我打算稍后使用它。)
package mainPackage;
import java.util.Random;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;
public class MainClass {
private static FileWriter fw;
private static BufferedWriter out;
private static Scanner input;
private static Scanner file;
private static Random slc;
public static void main(String[] args) throws IOException{
fw = new FileWriter("C:/Users/ALAN_BARE/Desktop/Dictionary.txt" , true );
input = new Scanner(System.in);
file = new Scanner(new File("C:/Users/ALAN_BARE/Desktop/Dictionary.txt"));
out = new BufferedWriter(fw);
slc = new Random();
String engword;
String gerword;
String response;
System.out.println("What do you want to do, register words or play the game?");
response = input.nextLine();
if(response.contains("register")){
System.out.println("Type yor english word:");
engword = input.nextLine();
System.out.println("Type the translation in German:");
gerword = input.nextLine();
out.write(engword);
out.write(gerword);
if(file.hasNextLine()){
out.newLine();
out.newLine();
out.write(engword);
out.write(" " + gerword);
} else{
out.write(engword);
out.write(" " + gerword);
}
} else if(response.contains("Register")){
System.out.println("Type yor english word:");
engword = input.next();
System.out.println("Type the translation in German:");
gerword = input.next();
if(file.hasNextLine()){
out.newLine();
out.newLine();
out.write(engword);
out.write(" " + gerword);
} else{
out.write(engword);
out.write(" " + gerword);
}
}
}
}
答案 0 :(得分:2)
关闭BufferedWriter。 out.close()
建议:
将以下代码放在if-else块之外,因为这些是常见的
out.write(engword);
out.write(" " + gerword);