打印到文本文件[重复]

Posted

技术标签:

【中文标题】打印到文本文件[重复]【英文标题】:Printing onto a text file [duplicate] 【发布时间】:2013-10-28 13:03:52 【问题描述】:

我创建了一个PrintWriter 和新的文本文件,并希望将我的答案打印到文本文件中。但是,由于代码嵌入在程序的循环中,每次重新启动循环时,都会创建一个新的文本文件来替换上一个文件。如何编写代码,以便每次循环重新开始时都不会重新创建文本文件?

这是我的代码:

public class Wordler 

    public static void main(String[] args) throws IOException

        //introduces the game
        System.out.println("Wordler: Finding words within a word");
        System.out.println(" ");
        System.out.println("Directions:");
        System.out.println("Create as many words as you can with the letters in the word given. Once you have written as many words as you can think of, type");
        System.out.println("'x' and then hit the enter key to end the game round. Good luck!");
        System.out.println("--------------------------------------------------------------------------------------------------------------------------");

        runGame();
    

    //method to run the game
    public static void runGame() throws FileNotFoundException

        //array list of arrays that contains all the possible words 
        ArrayList<String> wholeList = new ArrayList<String>();
        wholeList.add("vulnerability");
        wholeList.add("calculate");
        wholeList.add("virtual");

        //PrintWriter and File
        File results = new File("WordlerResults.txt");
        PrintWriter output = new PrintWriter(results);

        //list of words and their answers (as a sublist)
        ArrayList<String> arr1 = new ArrayList<String>();
        arr1.add("vulnerabiliy");
        arr1.add("ability");
        arr1.add("nearby");
        arr1.add("lite");
        arr1.add("near");
        arr1.add("bare");
        arr1.add("rule");
        arr1.add("bury");
        arr1.add("lair");
        arr1.add("rile");
        arr1.add("bear");
        arr1.add("liberality");
        arr1.add("virulently");
        arr1.add("vulnerably");
        arr1.add("inevitably");
        arr1.add("tenurially");
        arr1.add("inertially");
        arr1.add("neutrally");
        arr1.add("unlivable");
        arr1.add("unitarily");
        arr1.add("veniality");
        arr1.add("reliantly");
        arr1.add("brilliant");
        arr1.add("urinative");
        arr1.add("nailbiter");
        arr1.add("illuviate");
        arr1.add("unitively");
        arr1.add("veritably");
        arr1.add("trivially");
        arr1.add("vibratile");
        arr1.add("virtually");
        // stopped at #20, www.wordplays.com/w/13810606276/vulnerability

        List<String> arr1Sub = arr1.subList(1, 30); 

        ArrayList<String> arr2 = new ArrayList<String>();
        arr2.add("calculate");
        arr2.add("late");
        arr2.add("call");
        arr2.add("teal");
        arr2.add("talc");
        arr2.add("catcall");
        arr2.add("tall");
        arr2.add("cult");
        arr2.add("lace");
        arr2.add("tela");
        arr2.add("acute");
        arr2.add("lacteal");
        arr2.add("callet");
        arr2.add("acuate");
        arr2.add("luteal");
        arr2.add("actual");
        arr2.add("cullet");
        arr2.add("caecal");
        arr2.add("alulae");
        arr2.add("acetal");
        arr2.add("alate");
        arr2.add("caeca");
        arr2.add("aceta");
        arr2.add("eclat");
        arr2.add("cecal");
        arr2.add("lutea");
        arr2.add("cella");
        arr2.add("cleat");
        arr2.add("tulle");
        arr2.add("culet");
        arr2.add("alula");
        arr2.add("calla");
        arr2.add("tale");
        arr2.add("tace");
        arr2.add("celt");
        arr2.add("clue");
        arr2.add("alec");
        arr2.add("tell");
        arr2.add("cull");
        arr2.add("alae");
        arr2.add("cate");
        arr2.add("acta");
        arr2.add("tule");
        arr2.add("caca");
        arr2.add("ceca");
        arr2.add("tael");
        arr2.add("latu");
        arr2.add("lute");
        arr2.add("caul");
        arr2.add("cute");
        arr2.add("luce");
        arr2.add("cell");
        arr2.add("tala");

        List<String> arr2Sub = arr2.subList(1, 52);

        ArrayList<String> arr3 = new ArrayList<String>();
        arr3.add("virtual");
        arr3.add("ritual");
        arr3.add("vault");
        arr3.add("virtu");
        arr3.add("vital");
        arr3.add("trial");
        arr3.add("rival");
        arr3.add("viral");
        arr3.add("ultra");
        arr3.add("urial");
        arr3.add("trail");
        arr3.add("aril");
        arr3.add("vair");
        arr3.add("tali");
        arr3.add("virl");
        arr3.add("lair");
        arr3.add("rail");
        arr3.add("airt");
        arr3.add("vita");
        arr3.add("lati");
        arr3.add("vial");
        arr3.add("alit");
        arr3.add("tail");
        arr3.add("lair");
        arr3.add("rial");
        arr3.add("vatu");
        arr3.add("latu");
        arr3.add("tirl");
        arr3.add("ulva");
        arr3.add("litu");
        arr3.add("lira");
        arr3.add("lari");
        arr3.add("vail");

        List<String> arr3Sub = arr3.subList(1, 32);

        //input list
        ArrayList<String> inputList = new ArrayList<String>(); 
        Scanner input = new Scanner(System.in);

        //to print the words for the game
        int r = (int) (Math.random() * 2);
        String word = wholeList.get(r);
        System.out.println(word);

        while (input.hasNextLine())
            String words = input.nextLine();
            if (words.equalsIgnoreCase("x"))
                break;
            
            else
                inputList.add(words);
            
        

        //check answers
        ArrayList<String> validAnswers = new ArrayList<String>();
        ArrayList<String> wrongAnswers = new ArrayList<String>();
        ArrayList<String> notFound = new ArrayList<String>();
        List<String> compare = new ArrayList<String>();

        if (r == 0)
            compare = arr1Sub;
        
        else if (r == 1)
            compare = arr2Sub;
        
        else if(r == 2)
            compare = arr3Sub;
        
        else
            compare.add("error");
            System.out.println(compare);
        

        for (int i = 0; i < inputList.size(); i++)
            if (compare.contains(inputList.get(i))) 
                validAnswers.add(inputList.get(i));
            
            else if (!compare.contains(inputList.get(i)))
                wrongAnswers.add(inputList.get(i));
            
            else
                notFound.add(compare.get(i)); 
            
        

        System.out.println("Valid Answers: " + validAnswers);
        System.out.println("Wrong Answers: " + wrongAnswers);
        output.println(wholeList.get(r)); 
        output.println("Valid Answers: " + validAnswers);
        output.println("Wrong Answers: " + wrongAnswers);
        output.close();

        System.out.println(" ");
        System.out.println("Would you like to play again? (Y/N)");
        String response = input.nextLine();
        System.out.println(" ");

        if (response.equalsIgnoreCase("y"))
            repeatGame();
        
        else if (response.equalsIgnoreCase("n"))
            System.out.println(" "); 
            System.out.println("Thank you for playing!");
        
    

    public static void repeatGame()
        try 
            runGame();
         catch (FileNotFoundException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
    



【问题讨论】:

您只是想将其附加到文件中还是创建一个新文件? 【参考方案1】:

假设您希望通过将旧写入数据保留在文件中来附加数据:创建FileOutputStream(file, append) 的实例并用PrintWriter 包装它应该可以工作:

  PrintWriter writer = new PrintWriter(new FileOutputStream(myFile, true));
       writer.write("a String");
       writer.close();

【讨论】:

【参考方案2】:

开始游戏前将创建文件codez放入main 主要是这样的

public static void main(String[] args) throws IOException
...
File results = new File("WordlerResults.txt");
    PrintWriter output = new PrintWriter(results);
    runGame(output);

并且运行游戏接受输出作为输入参数

public static void runGame(PrintWriter output) throws FileNotFoundException
...
//also remove these two lines from here
//    File results = new File("WordlerResults.txt");
//    PrintWriter output = new PrintWriter(results);

但该文件仍将在下一次调用(应用程序运行)时被覆盖,因此您只需要检查文件存在状态,并将光标标记到末尾即可。

顺便说一句,不要忘记在编程生命周期结束时刷新和关闭输出

output.flush();
output.close();

【讨论】:

以上是关于打印到文本文件[重复]的主要内容,如果未能解决你的问题,请参考以下文章

将每个返回的字符串添加到文本文件中[重复]

如何计算文本文件中重复单词的频率?

在 python 中打印出文本文件会给出错误消息 -charmap_decode(input,errors,decoding_table) [重复]

为啥它只打印文本文件的一个单词而不是整个文本文件到 html 文件

删除重复的数组条目

在Java中更改打印流的区域设置[重复]