【发布时间】:2012-04-08 22:58:33
【问题描述】:
我可以将文本文件放在库项目的 res\raw 文件夹中,但读取它似乎需要上下文引用。有人可以对此有所了解吗?
【问题讨论】:
标签: android eclipse android-resources
我可以将文本文件放在库项目的 res\raw 文件夹中,但读取它似乎需要上下文引用。有人可以对此有所了解吗?
【问题讨论】:
标签: android eclipse android-resources
查看我的回答here,了解如何从 POJO 读取文件。
一般情况下,res 文件夹应该会被 ADT 插件自动添加到项目构建路径中。假设您有一个 test.txt 存储在 res/raw 文件夹下,可以在没有 android.content.Context 的情况下读取它:
String file = "raw/test.txt"; // res/raw/test.txt also work.
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
我之前使用旧的 SDK 版本进行过此操作,它也应该适用于最新的 SDK。试一试,看看是否有帮助。
【讨论】:
为了访问资源,您需要一个上下文。在这里查看 developer.android 站点中 Context.class 的定义
有关应用程序环境的全局信息的接口。这 是一个抽象类,其实现由 Android 提供 系统。它允许访问特定于应用程序的资源和 类,以及对应用程序级操作的向上调用,例如 发起活动、广播和接收意图等。
因此,您可以通过上下文访问资源文件。您可以创建另一个类并将上下文从活动传递给它。创建一个读取指定资源文件的方法。
例如:
public class ReadRawFile {
//Private Variable
private Context mContext;
/**
*
* Default Constructor
*
* @param context activity's context
*/
public ReadRawFile(Context context){
this.mContext = context;
}
/**
*
* @param str input stream used from readRawResource function
* @param x integer used for reading input stream
* @param bo output stream
*/
private void writeBuffer(InputStream str, int x, ByteArrayOutputStream bo){
//not hitting end
while(x!=-1){
//write to output buffer
bo.write(x);
try {
//read next
x = str.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @return output file to string
*/
public String readRawResource(){
//declare variables
InputStream rawUniversities = mContext.getResources().openRawResource(R.raw.universities);
ByteArrayOutputStream bt = new ByteArrayOutputStream();
int universityInteger;
try{
//read/write
universityInteger = rawUniversities.read();
writeBuffer(rawUniversities, universityInteger, bt);
}catch(IOException e){
e.printStackTrace();
}
//return string format of file
return bt.toString();
}
}
【讨论】:
2021 年可以获取没有上下文的原始文件
val Int.rawString: String
get(){
var res= ""
val `is`: InputStream = Resources.getSystem().openRawResource(this)
val baos = ByteArrayOutputStream()
val b = ByteArray(1)
try {
while (`is`.read(b) !== -1) {
baos.write(b)
}
res = baos.toString()
`is`.close()
baos.close()
} catch (e: IOException) {
e.printStackTrace()
}
return res
}
【讨论】: