1

我正在尝试读取 .txt 文件并将其附加到 ArrayList。它似乎在 Scanner 行失败并显示“java.io.FileNotFoundException:/raw/words.txt:打开失败:(没有这样的文件或目录)”。我尝试了 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));
    }
}
4

1 回答 1

2

是的,您不能像这样仅通过 raw/words.txt 来具体说明,android 的存储路径与台式机的存储路径不同

你需要获取他们的资源并阅读它

例如从这里复制

// 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();
     }
于 2013-05-06T20:56:26.943 回答