将ArrayList保存为.txt文件

时间:2015-03-23 15:30:04

标签: java arraylist

所以,我想知道是否可以将ArrayList中的值保存到文件中,例如“inputs.txt”。我已经看到了类似这样的问题:save changes (permanently) in an arraylist?但是这对我不起作用,所以我想知道我做错了什么。这是我的文件: Main.class

package noodlegaming.geniusbot.main;

import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Logger;

public class Main {

    public static Random rand = new Random();

    public static void readFileByLine(String fileName) {
        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext()) {
            SentencesToUse.appendToInputtedSentences(scanner.next().toString());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    static File inputsFile = new File("inputs.txt");

    static PrintWriter printWriter = new PrintWriter(inputsFile);

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

        if(!inputsFile.exists()) {
            inputsFile.createNewFile();
        }

        readFileByLine("inputs.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Hello, welcome to GeniusBot. Shortly, you will be speaking with a computer that learns from what you say.");
        System.out.println("Because of this circumstance, we ask that you do not type any curses, swear words, or anything otherwise considered inappropriate,");
        System.out.println("as it may come back to the light at a time you don't want it to.");
        System.out.println("Please note that your responses won't be saved if you close the program.");
        System.out.println("If you type printInputsSoFar, a list of all the stuff you've typed will be printed.");
        System.out.println("If you type printInputsLeft, the number of inputs you have left will be printed.");
        System.out.println("If you type clearInputs, the program will be closed and the inputs.txt file deleted, " +
            "\nand recreated upon startup.");
        System.out.println("Starting up GeniusBot.");
        Thread.sleep(3000);
        System.out.println("Hello! I am GeniusBot!");
        br.readLine();
        System.out.println("" + SentencesToUse.getBeginningSentence() + "");

        for (int i = 0; i < 25; i++) {
            String response = br.readLine();

            if (response.equals("printInputsSoFar")) {
                for (int j = 1; j < SentencesToUse.inputtedSentences.size();    j++) {
                    System.out.println(SentencesToUse.inputtedSentences.get(j));
                }
                i--;
            } else if (response.equals("printInputsLeft")) {
                int inputsLeft = 25 - i;
                System.out.println("You have " + inputsLeft + " inputs left.");
                i--;
            } else if (response.equals("clearInputs")) {
                printWriter.close();
                inputsFile.delete();
                Thread.currentThread().stop();
            } else {
                SentencesToUse.appendToInputtedSentences(response);
                printWriter.println(response);
                printWriter.flush();

                int inputtedSentence = Main.rand.nextInt(SentencesToUse.inputtedSentences.size());
                String inputtedSentenceToUse = SentencesToUse.inputtedSentences.get(inputtedSentence);
                System.out.println(inputtedSentenceToUse);
            }

            if (i == 24) {
                System.out.println("Well, it was nice meeting you, but I have to go. \nBye.");
                Thread.currentThread().stop();

                printWriter.close();
            }
        }
    }
}

SentencesToUse.class:

package noodlegaming.geniusbot.main;

java.util.ArrayList;
import java.util.List;

public class SentencesToUse {

    public static String[] beginningSentences = {"What a lovely day!", "How are you?", "What's your name?"};

    static int beginningSentence = Main.rand.nextInt(beginningSentences.length);
    static String beginningSentenceToUse = beginningSentences[beginningSentence];

    public static String getBeginningSentence() {
        return beginningSentenceToUse;
    }

    public static List<String> inputtedSentences = new ArrayList<String>();

    public static void appendToInputtedSentences(String string) {
        inputtedSentences.add(string);
    }

    public static void clearInputtedSentences() {
        inputtedSentences.clear();
    }

}

1 个答案:

答案 0 :(得分:0)

如评论中所述,使用PrintWriter将值写入文件:

PrintWriter pw = new PrintWriter(fos);
for (int i = 0; i < SentencesToUse.inputtedSentences.size(); i++) {
    pw.write(SentencesToUse.inputtedSentences.get(i)+"\n"); // note the newline here
}
pw.flush(); // make sure everything in the buffer actually gets written.

然后,再次阅读它们:

try {
    Scanner sc = new Scanner(f);

    while (sc.hasNext()) {
        SentencesToUse.inputtedSentences.ass(sc.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

pw.flush();非常重要。当我第一次学习java时,我无法告诉你我花了多少时间进行调试,因为我没有冲洗流。另请注意"\n"。这确保了会有一个换行符,并且你的句子不会在一个巨大的blob中一起运行。如果每个人都有一个换行符,则没有必要。与print vs println不同,没有writeln。您必须手动指定换行符。