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 楼答案
因为您没有提供文本文件的路径。您必须将其放在项目的根目录中
您应该删除方法
readTextFile
中的行txtEditor.setText(reader.toString());
,原因有二:reader.toString()
不会提供读取器中包含的文本,但会打印对象(getClass().getName() + '@' + Integer.toHexString(hashCode()
)的内存地址,因为toString()
方法是从Object
类直接继承的因此,创建一个保存该字符串的变量,并将其设置为
EditText
。