我在我的/ res/raw /文件夾(/res/raw/textfile.txt)中有一個資源文件,我試圖從我的android應用程序讀取進行處理。訪問Android中的資源文件
public static void main(String[] args) {
File file = new File("res/raw/textfile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Do something with file
Log.d("GAME", dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
我已經嘗試了不同的路徑語法,但總是得到java.io.FileNotFoundException錯誤。我如何訪問/res/raw/textfile.txt進行處理?是文件文件=新文件(「res/raw/textfile.txt」); Android中的錯誤方法?
*答:*
// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
public void LoadText(int resourceId) {
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
考慮我們[Apache Commons](http://commons.apache.org/proper/commons-io/)。在那裏搜索'IOUtils'。 – JJD 2013-10-08 14:39:55