2010-09-14 133 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文件。 //此代码终于解决了我的简单文本加载问题