2013-05-06 113 views
1

我尝试读txt文件,并追加到一个ArrayList。这似乎在与扫描线失败“java.io.FileNotFoundException:/raw/words.txt:打开失败:(没有这样的文件或目录)”。我试过了BufferReader方法,并且很少成功地改变文件的位置。为什么不识别文件?阅读txt文件列出的Android/FileNotFound

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)); 
    } 
} 
+1

哪里是你的文件复制? – 2013-05-06 20:53:11

+0

RES /生/ words.txt – ono 2013-05-06 20:55:19

+0

刚刚发现这一点。它可以帮助http://stackoverflow.com/questions/5771366/reading-a-simple-text-file – ono 2013-05-06 20:55:37

回答

2

是的,你可以不通过特定的那样只是原始/ 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(); 
    }