有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用文本文件

我想读取文本文件并在“编辑文本”中显示它,但我不知道将文本文件放在项目中的何处,在这之后,如何调用文本文件以进行读写操作

我得到了错误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) 个答案

  1. # 1 楼答案

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

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

    • reader.toString()不会提供读取器中包含的文本,但会打印对象(getClass().getName() + '@' + Integer.toHexString(hashCode())的内存地址,因为toString()方法是从Object类直接继承的

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


    因此,创建一个保存该字符串的变量,并将其设置为EditText
    String text = readTextFile("test.txt");    
    txtEditor.setText(text);