我正在尝试在Android工作室中读取文件并将每个字符串放入arraylist但是当我尝试从arraylist中获取字符串时,应用程序崩溃(消息:"不幸的是,App已停止")谁能告诉我什么是错的?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////////////////////////////////////////////////////////////////////////////
String text = "";
tv_view = (TextView) findViewById(R.id.textview1);
Scanner s = new Scanner(System.in);
File n = new File("C:\\Users\\Admin\\AndroidStudioProjects\\LOTOS.1\\app\\src\\main\\assets\\nouns.txt");
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
s = new Scanner(n);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Instantiate a new ArrayList of String type
ArrayList<String> theWord = new ArrayList<String>();
//while it has next ..
while(s.hasNext()){
//Initialise str with word read
String str=s.next();
//add to ArrayList
theWord.add(str);
}
text = theWord.get(150);
tv_view.setText(text);
//return ArrayList
}
答案 0 :(得分:0)
问题是您无法直接从Android系统中的Windows系统读取文件。 Android设备和Windows是完全不同的系统。即使您已将文件放在assets
文件夹中,也无法读取它,因为路径引用了Windows结构。
您的Android设备或模拟器无法读取此路径:C:\\Users\\Admin...
要从Android Studio中的assests
访问文件,您应该使用getAssets().open(...)
方法。
以下是您可以阅读文件的示例。
BufferedReader reader = null;
reader = new BufferedReader(
new InputStreamReader(getAssets().open("nouns.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process
...
}