我正在尝试读取android上的文件

时间:2013-04-05 02:55:44

标签: android button text file-io textview

我正在创建一个应用程序,其中按钮的文本是随机字符串,并且所有随机字符串都存储在.txt文件中。我创建了一个返回字符串的方法,出于某种原因,每当我运行应用程序时,按钮都是空白的,并且没有文本。我知道这与文件io有关,因为如果我得到方法返回一个类似于&#34的设置字符串;嗨"那么按钮上的文字就好了。我正在添加我的oncreate方法以防万一。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    String str = "Hello there!";
    TextView text = (TextView) findViewById(R.id.question);
    text.setText(execute());

}

上面是我的oncreate,下面是我的文件档案

public static String execute() {
 String number[] = new String[100];
 double x = Math.random()*47;
 int random = (int) Math.round(x);

    int act = 0;

    //The try/catch statement encloses some code and is used to handle errors and exceptions that might occur
    try { 

        // Read in a file
        BufferedReader in = new BufferedReader(new FileReader("activities")); 

        String str; 
        while ((str = in.readLine()) != null) { 
            number[act] = str;
            act++;
        } 
        in.close();
        } catch (IOException e) { 
            System.out.println("Can not open or write to the file.");
        } 



    return number[random];
}

1 个答案:

答案 0 :(得分:2)

您已经提到尝试从.txt文件中读取,但在FileReader中,您只提供了一个名为activities的名称而没有任何文件扩展名。这就是为什么没有显示出来的原因。

new FileReader("activities.txt"); // Should be something like this

此外,它需要是相对URL甚至更好,尝试将您的文件放在assets文件夹中,然后尝试从那里读取它。这是一种更好,更清洁的方法。

请查看此answer,了解如何从assets文件夹中读取文件。

相关问题