我如何使用文本文件

时间:2013-06-07 10:57:53

标签: java android eclipse file-io

我想阅读文本文件并在编辑文本中显示它,但我不知道将文本文件放在项目中的位置,之后,如何调用文本文件进行读写?

我收到错误No such file or directory

这是我到目前为止所做的:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     txtEditor=(EditText)findViewById(R.id.textbox);
     readTextFile("test.txt");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public String readTextFile(String fileName) {

      String returnValue = "";
      FileReader file = null;

      try {
        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);
        String line = "";
        while ((line = reader.readLine()) != null) {
          returnValue += line + "\n";
        }
        txtEditor.setText(reader.toString());
      } catch (Exception e) {
          throw new RuntimeException(e);
      } finally {
        if (file != null) {
          try {
            file.close();
          } catch (IOException e) {
            // Ignore issues during closing 
          }
        }
      }
      return returnValue;
    } 

1 个答案:

答案 0 :(得分:1)

由于您没有为文本文件提供路径。您必须将它放在项目的根目录中。

您应该删除方法txtEditor.setText(reader.toString());中的行readTextFile,原因有两个:

  • reader.toString()不会为您提供阅读器中包含的文本,但它会打印对象的内存地址(getClass().getName() + '@' + Integer.toHexString(hashCode()),因为toString()方法是从{继承的{方法} {1}}班。

  • 该方法已经返回文件中包含的文本。

<小时/> 因此,创建一个包含此字符串的变量,并将其设置为Object

EditText
相关问题