我正在尝试读取.txt文件并将其附加到ArrayList。它似乎在Scanner行中失败了'java.io.FileNotFoundException:/raw/words.txt:open failed :(没有这样的文件或目录)'。我尝试过BufferReader方法并改变文件的位置但收效甚微。为什么不识别文件?
public void openFile (){
File file = new File("raw/words.txt");
ArrayList<String> names = new ArrayList<String>();
try{
Scanner in = new Scanner (file);
while (in.hasNextLine()){
names.add(in.nextLine());
}
}
catch (Exception e){
e.printStackTrace();
}
Collections.sort(names);
for(int i=0; i<names.size(); ++i){
System.out.println(names.get(i));
}
}
答案 0 :(得分:2)
是的,你不能仅仅通过raw / words.txt具体来说,android不存储路径与桌面pc相同
你需要获取他们的资源并阅读它
例如来自here
的副本// to call this method
// String answer = readRawTextFile(mContext, R.raw.words);
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}