不会写入文件?

Won't write to file?

所以,我正在尝试创建这个应用程序,但仍处于开始阶段,但每次我 运行 它并尝试写入文件 Dictionary.txt 时,该文件将是完全是空的。它会在我做的另一件事中起作用,但在这里它只是 运行s 很好,被终止,当我打开文件时它是空白的,未写的。目前在 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);
            }
        }
    }
}

关闭 BufferedWriter。 out.close()

建议:

将以下代码放在 if-else 块之外,因为这些很常见

out.write(engword);
out.write(" " + gerword);