Reputation: 151
i want to read the text file and show it on edit-text but I don't know where to place the text file in project and after that, how can I call the text file for read and write purposes?
I am getting the error No such file or directory
.
This is what i have done so far:
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;
}
Upvotes: 0
Views: 51
Reputation: 93842
Since you provided no path for the text file. You have to place it at the root of your project.
You should remove the line txtEditor.setText(reader.toString());
in the method readTextFile
for two reasons :
reader.toString()
won't give you the text contained in the reader but it will prints the memory address of the object (getClass().getName() + '@' + Integer.toHexString(hashCode()
) because the toString()
method is direclty inherited from the Object
class.EditText
.
String text = readTextFile("test.txt");
txtEditor.setText(text);
Upvotes: 1