简体   繁体   English

将ArrayList保存到.txt文件

[英]Saving an ArrayList to .txt file

So, I was wondering if it's possible to save values from an ArrayList to a file, such as "inputs.txt". 因此,我想知道是否可以将ArrayList中的值保存到文件中,例如“ inputs.txt”。 I've seen a question similar to this: save changes (permanently) in an arraylist? 我见过类似的问题: 将更改(永久)保存在arraylist中吗? , however that didn't work for me, so I'm wondering if I'm doing something wrong. ,但这对我不起作用,所以我想知道我做错了什么。 Here are my files: Main.class 这是我的文件: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: 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();
    }

}

As stated in the comments, use a PrintWriter to write the values to a file instead: 如注释中所述,请使用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.

And then, to read them back again: 然后,再次阅读它们:

try {
    Scanner sc = new Scanner(f);

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

The pw.flush(); pw.flush(); is incredibly important. 非常重要。 When I was first learning java, I can't tell you how many hours I spent debugging because I didn't flush my streams. 当我第一次学习Java时,我无法告诉您我花了多少时间进行调试,因为我没有刷新流。 Note also the "\\n" . 注意"\\n" This ensures that there will be a newline, and that your sentences don't just run together in one giant blob. 这样可以确保有一个换行符,并且您的句子不会只是在一个巨大的Blob中一起运行。 If each one already has a newline, then that's not necessary. 如果每个人都已经有一个换行符,则没有必要。 Unlike print vs println, there is no writeln. 与print vs println不同,没有writeln。 You must manually specify the newline character. 您必须手动指定换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM