2010-09-14 130 views
2

我想從資源中讀取文件「words.txt」。這是一個非常簡單但很大(2 MB)的文本文件,我想逐行閱讀。我已經把文件分成/res/raw/words.txt,並嘗試用下面的代碼打開它:作爲資源讀取文本文件

try 
    { 
     BufferedReader in = 
      new BufferedReader(
      new InputStreamReader(getResources().openRawResource(R.raw.words))); 
     String line=in.readLine(); 
     T.append(line); T.append("\n"); 
     in.close(); 
    } 
    catch (Exception e) { T.append(e.toString()); } 

不過,我得到一個java.io.IOException異常。這不是「未找到資源」異常,所以資源可以正確打開,但readLine()會產生錯誤。

我試着使用InputStream本身,其結果是read()產生-1,代表EOF,就好像文件是空的一樣。

對我有幫助嗎?


直到現在我仍然分裂長文件。所以這是我能給出的最佳答案。任何人有更好的主意?

回答

3

試試這個:

InputStream is = c.getResources().openRawResource(R.raw.csv_file); 
     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
     String readLine = null; 

     try { 
      while ((readLine = br.readLine()) != null) { 


      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
+1

'c'我認爲是'Context' ... – st0le 2010-09-14 09:24:45

+0

是的,對於混亂的抱歉 - 作品? – 2010-09-14 11:23:06

+0

不,不起作用。無論如何,我會感到驚訝,因爲資源被找到並正確打開。只是,系統假裝它是空的。 – Rene 2010-09-14 13:12:45

0

//聲明你的負載功能

public String teststring; 
public int loadcounter; 

的這些外部//我把這個代碼在GL表面負載功能

//加載功能 // note c changed to work for worky

InputStream is = context.getResources().openRawResource(R.raw.ship1); 
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
    String readLine = null; 

    try { 
     while ((readLine = br.readLine()) != null) { 

      if(loadcounter ==0) 
      { 
       teststring=br.readLine();//get first line to printable string 
        //this code works 
        //array[loadcounter] = br.readLine(); 
       //want to get this remarked part working for level load 
       } 
     loadcounter++; //var will increment an array 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); //create exception output 
    } 

//我使用了文件ship1.txt。您需要在資源文件夾中創建一個原始文件夾,然後//在那裏創建一個ship1.txt文件。 //此代碼終於解決了我的簡單文本加載問題