正在读取.txt文件以列出Android/FileNotFound
我试图读取一个.txt文件并将其附加到ArrayList。它似乎在扫描程序行失败,出现“java.io.FileNotFoundException:/raw/words.txt:openfailed:(没有这样的文件或目录)”。我尝试了BufferReader方法并更改了文件的位置,但收效甚微。为什么它不能识别文件正在读取.txt文件以列出Android/FileNotFound,android,arraylist,Android,Arraylist,我试图读取一个.txt文件并将其附加到ArrayList。它似乎在扫描程序行失败,出现“java.io.FileNotFoundException:/raw/words.txt:openfailed:(没有这样的文件或目录)”。我尝试了BufferReader方法并更改了文件的位置,但收效甚微。为什么它不能识别文件 public void openFile (){ File file = new File("raw/words.txt"); ArrayList<String
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));
}
}
public void openFile(){
File File=新文件(“raw/words.txt”);
ArrayList name=新的ArrayList();
试一试{
扫描仪输入=新扫描仪(文件);
while(在.hasNextLine()中){
name.add(in.nextLine());
}
}
捕获(例外e){
e、 printStackTrace();
}
集合。排序(名称);
对于(int i=0;i是的,你不能像那样仅仅通过raw/words.txt来指定,android存储路径与台式pc不一样
你需要得到他们的资源并阅读它
例如,从
刚找到这个。这可能会有帮助。不,在那个示例中,他们将文件存储在asset/not-in-raw/中。要访问原始资源,请使用resources.openRawResource()
使用资源ID,即R.raw.filename
。或者您可以将文件移动到assets
目录并使用AssetManager
获取它。这些文件位于APK中,它们不在文件系统中,因此您不能简单地创建file
对象并打开它。
// 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();
}