我试图让我的Android应用程序从文本文件中读取并随机选择一个条目然后显示它,我该怎么做呢?我想我必须使用缓冲读取器或输入流命令,但我不知道如何使用这些,我已经尝试谷歌搜索但没有找到很多帮助。
据我所知(并提供一些帮助),我必须阅读文本文件,将其添加到字符串中?并使用以下命令随机选择一个条目
Random.nextInt(String[].length-1).
我该怎么做呢? :\ im对所有这些缓冲区读取器的东西都很新。
答案 0 :(得分:6)
您在这里询问两种不同的操作。不要把问题弄糊涂在一起弄乱问题。你想知道如何:
从一组字符串中随机选择1个字符串。
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("inputfile.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
String randomString = lines.get(r.nextInt(lines.size()));
答案 1 :(得分:0)
这是从文本文件中读取的一些快速代码。你需要将它修改为在线分割,显然现在解决TODO是好的,但它应该让你开始。
try
{
InputStream is = new FileInputStream(m_file);
if(m_is == null)
{
openInputStream();
}
StringBuilder sb = new StringBuilder();
//TODO: get a buffered stream going, it should be more efficient
byte[] buf = new byte[100];
int readLen;
while((readLen = is.read(buf, 0, 100)) != -1)
{
sb.append(new String(buf, 0, readLen));
}
closeInputStream();
return sb.toString();
}
catch (FileNotFoundException e)
{
//TODO: handle this
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
}
}
答案 2 :(得分:-1)
/*This sample code shows how to read one term and its definition from
the file using TextIO.
The code just reads the term and the definition in to a String.
To read the whole file the simplest solution is to have an array
of String for the terms and an array of String for the definitions
and to ensure that you store the definition for a term at the same
index position in the definitions array as you store the term it
defines in the term array.
If you find that the TextIO window is too narrow to display the whole
of some of the lines of the definition on one line you can edit the text
file sothat each line contains fewer words (this may depend on your
screen resolution).
*/
public class Read from a txt file {
public static void main(String[]args){
String term = "";
String definition = "";
TextIO.readFile("Your_file.txt");
TextIO.putln("Just read this term from file: " + term);
String str;
do {
str = TextIO.getln();
definition = definition + str + "\n";
} while (str.length() != 0);
TextIO.putln(definition);
// Once you have read all the file take input from keyboard:
TextIO.readStandardInput();
}
}