我无法将答案添加到readwrite.txt。有什么方法可以做到吗?

时间:2018-12-27 20:49:37

标签: java filewriter

我尝试将答案添加到readwrite.txt,但是每次运行代码时都找不到答案。

public static void main(String[] args) {
// write your code here

    ArrayList<String> category1=new ArrayList<>();
    category1.add("die hard");
    category1.add("7.5");
    category1.add("mission impossible");
    category1.add("8");
    category1.add("the expendabels");
    category1.add("6");
    ArrayList<String> category2=new ArrayList<>();
    category2.add("the mask");
    category2.add("due date");
    ArrayList<String>userchoices=new ArrayList<>();
    Scanner s= new Scanner(System.in);
    //System.out.println("type user name");
    //String name=s.nextLine();
    System.out.println("select a movie");
    String answer=s.nextLine();


    String writepath="files/readwrite.txt";

    try {

        FileWriter writer=new FileWriter(writepath);
        writer.write(answer);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (category1.contains(answer)) {
        System.out.println(category1.get(category1.indexOf(answer) + 1) + (" of 10"));
        System.out.println("action");
    }if (answer.equals("action"))
        System.out.println(category1);
    else if (category2.contains(answer))
        System.out.println("comedy");
    if (answer.equals("comedy"))
        System.out.println(category2);


}

}

我尝试将答案添加到readwrite.txt,但是每次运行代码时都找不到答案。

1 个答案:

答案 0 :(得分:0)

写完文件后,需要关闭FileWriter。当您调用close()时,writer将其内部缓冲区刷新到磁盘,并且您会看到文本出现在文件中。另外,当您不需要任何资源时,必须关闭它们。