Tôi có tệp tài nguyên trong/res/raw/folder (/res/raw/textfile.txt) mà tôi đang cố gắng đọc từ ứng dụng Android của mình để xử lý.Truy cập các tệp tài nguyên trong 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();
}
}
Tôi đã thử cú pháp con đường khác nhau nhưng luôn có được một java.io.FileNotFoundException lỗi. Tôi có thể truy cập /res/raw/textfile.txt để xử lý như thế nào? Là Tệp tệp = tệp mới ("res/raw/textfile.txt"); phương pháp sai trong Android?
* Trả lời: *
// 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();
}
}
Hãy xem xét chúng tôi ing [Apache Commons] (http://commons.apache.org/proper/commons-io/). Tìm kiếm 'IOUtils' ở đó. – JJD