在文本文件中显示特定行 - android / java

时间:2015-06-09 08:27:10

标签: java android string text

我正在尝试构建一个从文本文件中显示有趣事实的应用。为此,我得到一个随机数,然后显示文件中的特定行号。当我运行应用程序并尝试按下按钮时,我得到的是一个空白文本字段。这是我的代码:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fun_facts);
    // Declare and assign variables
    final TextView factLabel = (TextView) findViewById(R.id.factTextView);
    Button showFactButton =  (Button) findViewById(R.id.showFactButton);
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*
            code here runs when button click is detected by line 29
            code shows new fact
            */
            String fact = "";
            //get a random number to select a fact
            Random randomNumberGenrator = new Random();//construct random object
            int randomNumber = randomNumberGenrator.nextInt(391);
            FileReader fr = null;
            try {
                fr = new FileReader("facts.txt ");//construct filereader and assign file
            } catch (FileNotFoundException e) {
                e.printStackTrace();//exception raised
            }
            LineNumberReader getFact = new LineNumberReader(fr);//construct lineNumberReader
            getFact.setLineNumber(randomNumber);//set current line number to random number
            try {
                fact = getFact.readLine();//read current line and assign it to fact
            } catch (IOException e) {
                e.printStackTrace();
            }
            factLabel.setText(fact);
            try {
                getFact.close();//close lineReader
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fr.close();//close fileReader
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    showFactButton.setOnClickListener(listener);
}

1 个答案:

答案 0 :(得分:0)

你有任何错误吗?

检查这一行,也许是它的错误,但值得检查并从路径中删除该空格。 旧: fr = new FileReader(“facts.txt”); 新: fr = new FileReader(“facts.txt”);