从Res文件夹中读取文件

问题描述:

我在RAW文件夹中放置了一个“template.html”文件,我想将它读入InputStream。但它是返回null。不明白什么是错在下面的代码从Res文件夹中读取文件

e.g. fileName passed as parameter is "res/raw/testtemplate.html" 

public String getFile(String fileName) { 
    InputStream input = this.getClass().getClassLoader().getResourceAsStream(fileName); 
    return getStringFromInputStream(input); 
} 

此外,还有可能通过把这些文件放在一个特定的子文件夹,并把它的资产文件夹内是一个更好的解决方案,但后来我相信我会需要通过上下文在AssetManager中。我不明白这个解决方案,对不起我是android开发新手。有人可以阐明如何实现这种方法。

编辑

我已经开始实施与资产这一解决方案。下面的方法应该返回一个字符串,其中包含存储为template.html文件的整个文本。

的GetFile( “template.html”)//我送延长这段时间

问题得到错误getAssets()是不确定的。

public String getFile(String fileName) { 

    BufferedReader reader = null; 
    StringBuilder sb = new StringBuilder(); 
    String line; 
    try { 
      reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName))); 
      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 
     } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    return sb.toString(); 

} 
+0

可能重复[如何读取资源文件/ raw by name](http://*.com/questions/15912825/how-to-read-file-from-res-raw-by-name) – 2014-10-28 08:12:22

使用本

new BufferedInputStream(getResources().openRawResource(filepath)); 

这会返回一个缓冲的输入流

为了这个目的,采用资产文件夹:

资产/

这是空的。您可以使用它来存储原始资产文件。这里保存的文件按原样编译为.apk文件,并保留原始文件名。您可以像使用URI的典型文件系统一样导航此目录,并使用AssetManager将文件作为字节流读取。例如,这对于纹理和游戏数据来说是一个很好的位置。

所以,你可以很容易获得在资产方面获得:context.getAssets()

BufferedReader reader = null; 
try { 
    reader = new BufferedReader(
     new InputStreamReader(context.getAssets().open("filename.txt"))); 

    } 
} catch (IOException e) { 
    //log the exception 
} finally { 
    if (reader != null) { 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      //log the exception 
     } 
    } 
} 
+0

我试着实现你的解决方案。 getAssets未定义错误即将到来。我需要导入一些东西吗? – kafan1986 2014-10-28 09:02:06

+0

您必须创建资产文件夹:src/main/assets(用于Android Studio),并尝试http://developer.android.com/reference/android/content/Context.html#getAssets() – Tpec1k 2014-10-28 09:39:09

+0

请通过Edit在主体问题body getAssets方法未定义。编译之前即将出现错误。 – kafan1986 2014-10-28 10:09:33

的文件名应该是不带扩展

InputStream ins = getResources().openRawResource(
       getResources().getIdentifier("raw/FILENAME_WITHOUT_EXTENSION", 
       "raw", getPackageName()));