我正在创建一个处理文本文件的应用。基本上我开始尝试从文本文件中读取文本并在文本视图中显示它,但文本不会出现。我想,不过我可能会提到我想要实现的最终版本。
基本上在我的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);
}
}
答案 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之间的随机整数。