如何从文本文件中随机选择一段文本

时间:2018-06-13 11:31:02

标签: java android

我正在创建一个处理文本文件的应用。基本上我开始尝试从文本文件中读取文本并在文本视图中显示它,但文本不会出现。我想,不过我可能会提到我想要实现的最终版本。

基本上在我的assets/files文件夹中,我有一个名为jokes.txt

的文本文件

文本文件包含3个笑话,如下所示:

Teacher: "Kids, what does the chicken give you?"
Student: "Meat!"
Teacher: "Very good! Now what does the pig give you?"
Student: "Bacon!"
Teacher: "Great! And what does the fat cow give you?"
Student: "Homework!"


My friend thinks he is smart. He told me an onion is the only food that makes you cry, so I threw a coconut at his face.


A child asked his father, "How were people born?" So his father said, "Adam and Eve made babies, then their babies became adults and made babies, and so on." The child then went to his mother, asked her the same question and she told him, "We were monkeys then we evolved to become like we are now." The child ran back to his father and said, "You lied to me!" His father replied, "No, your mom was talking about her side of the family."

我想要做的是,当加载Content页面时,它会在文本视图content_text中随机显示其中任何一个笑话。

用户阅读笑话,如果他们选择按钮selectAnotherButton,则会从同一文本文件中随机选择一个笑话并将其显示在屏幕上,替换之前的笑话。

如何实施?下面我尝试从文件中进行基本读取,然后在textview中设置文本?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_content);

    Button backButton = findViewById(R.id.button_back);
    Button selectAnotherButton = findViewById(R.id.button_select_another);

    TextView contentText = findViewById(R.id.content_text);

    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            backToMainActivity();
        }
    });

    try {
        // file to inputstream
        InputStream input = getAssets().open("jokes.txt");
        // myData.txt can't be more than 2 gigs.
        int size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        input.close();
        // byte buffer into a string
        String text = new String(buffer);
        contentText.setText(text);
    }
    catch (Exception e) {
        System.out.println(e);
    }

}

2 个答案:

答案 0 :(得分:0)

  

我建议你将代码划分为函数:

public static String[] readAllFileIntoArray(String filename) {
    return FileUtils.readLines(new File(filename), "utf-8");
}

public static String randomChoice(String[] array) {
    java.util.Random random = new java.util.Random();
    int index = random.nextInt(array.length);
    return array[index];
}

public static String fileRandomChoice(String filename) {
    String[] file_lines = readAllFileIntoArray(filename);
    return randomChoice(file_lines);
}

答案 1 :(得分:0)

关于如何选择随机笑话并显示它们的部分我可以建议如下:

  • 在你的文本文件中,用符号分隔每个笑话(例如这个#)。
  • 然后读取整个文件并检查文件中有多少分隔符(在您的示例中有三个笑话,因此有三个分隔符)。
  • 最后你可以调用Random类给你一个1到3之间的随机整数。
  • 在知道笑话的编号后,您将获得所选分隔符的位置,并将文本从开始位置复制到分隔符的位置。