I am trying to read a text file that is already saved in my directory and print it on the screen as a TextView. This is the code that I have so far. However, when I run the application, it creates a toast which says "Error Reading File". What am I doing wrong here?
public class sub extends Activity {
private TextView text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
//text = (TextView) findViewById(R.id.summtext);
//File file = new File("inputNews.txt");
//StringBuilder text = new StringBuilder();
try {
InputStream in = openFileInput("inputNews.txt");
if(in != null){
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
in.close();
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
TextView output= (TextView) findViewById(R.id.summtext);
output.setText((CharSequence) text);
}
}

If you want to keep a .txt file in your Project, you must locate it in the assets folder.
Then you can access it with AssetManger .
Read this topic on how to create your assets folder, and then use this code:
public class subActivity extends Activity {
private TextView textView;
private StringBuilder text = new StringBuilder();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("inputNews.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
TextView output= (TextView) findViewById(R.id.summtext);
output.setText((CharSequence) text);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With