我正在尝试读取已保存在我的目录中的文本文件并将其作为 TextView 打印在屏幕上。这是我到目前为止所拥有的代码。但是,当我运行该应用程序时,它会创建一个 toast,上面写着“读取文件时出错”。我在这里做错了什么?
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);
}
}
如果你想保留一个.txt
文件在您的项目中,您必须将其找到assets
folder.
然后你可以通过以下方式访问它资产管理器 .
Read this关于如何创建您的主题assets
文件夹,然后使用以下代码:
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)