【问题标题】:Read text file as resource读取文本文件作为资源
【发布时间】:2010-09-14 08:36:29
【问题描述】:

我正在尝试从资源中读取文件“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,就好像文件是空的一样。

对我有什么帮助吗?


直到现在我还在拆分长文件。所以这是我能给出的最佳答案。谁有更好的主意?

【问题讨论】:

    标签: android


    【解决方案1】:

    试试这个:

    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();
            }
    

    【讨论】:

    • 不,不起作用。无论如何我都会感到惊讶,因为找到并正确打开了资源。只是,系统假装它是空的。
    • 但是我找到了原因。我缩短了文件,突然间,它开始工作了。现在我必须找出这是Android的限制,Eclipse的限制或设置,还是文件本身的问题。
    • 我已将文件分成 3 份,现在一切正常。为什么?我还不知道。
    • 您可能希望将文件下载到 SD 卡并读取它(通过相同的代码)
    • @Rene yup BufferedReader 仅将缓冲区大小限制为 8192 个字符,因此当缓冲区已满时,它会被刷新/错误并且不会加载数据。
    【解决方案2】:

    //在你的加载函数之外声明这些

    public String teststring;
    public int loadcounter;
    

    //我把这段代码放在一个gl表面加载函数中

    //加载函数 //注意c更改为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。 //这段代码终于解决了我简单的文本加载问题

    【讨论】:

      猜你喜欢
      • 2013-03-21
      • 2011-05-04
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多