从文件中读取并显示随机一行

3
我正在尝试让我的Android应用程序从文本文件中读取并随机选择一个条目,然后显示它。我该如何做?我认为我必须使用缓冲读取器或输入流命令,但我不知道如何使用这些命令,我已经尝试过谷歌搜索,但没有找到太多帮助。
据我所知(在一些帮助下),我必须读取文本文件,将其添加到一个字符串中,并使用以下命令随机选择一个条目。
Random.nextInt(String[].length-1).

我该如何做这个?:\ 我对于所有这些缓冲读取器等内容都很新手。


啊,太遗憾了,Android不支持java.nio.file.Files.readAllLines - Adam
3个回答

6

您在这里询问了两个不同的操作。不要混淆它们,使问题更加复杂。您想知道如何:

  1. Read a file from disk into a group of strings.
  2. Randomly choose 1 string from a group of strings.

    // 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()));
    

顺便说一下,为了清晰起见,我已经忽略了所有的try/catch。 - wolfcastle

0

这里是一些快速的代码,用于从文本文件中读取内容。你需要修改它以便在行末进行分割,并且显然最好解决一下TODOs,但这应该可以让你开始了。

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)
    {
    }
}

-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();
}
}

3
您确定 "Read from a txt file" 是一个有效的类名(包含空格)吗?我没有更改它,因为我不想改变您的代码。 - Paras
从txt文件中读取绝对是一个无效的类名 ;) - Pieter De Bie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接