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



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

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

你得到任何错误吗?

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

最新更新