#android #java #файлы
В простом Java приложении все просто. Используется BufferReader.
try {
BufferedReader in = new BufferedReader(new FileReader("dictionary.txt"));
while ((word = in.readLine()) != null) {
dictionary.put(word, 0);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
И тогда все строки файла записаны в HashMap, с которым дальше работаем.
Но как сделать так, что бы Android увидел этот файл. Файл лежит в папке asset. Как
бы логично что:
try {
AssetManager assetManager;
BufferedReader in = new BufferedReader(assetManager.open("dictionary.txt"));
while ((word = in.readLine()) != null) {
dictionary.put(word, 0);
}
in.close();
//assetManager.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Но нет, ошибка. Как достать этот файл?
UPD *SOLVED*
Метод:
public static void loadDictionary (Context context) throws IOException {
try {
AssetManager assetManager = context.getAssets();
InputStreamReader istream = new InputStreamReader(assetManager.open("dictionary.txt"));
BufferedReader in = new BufferedReader(istream);
while ((word = in.readLine()) != null) {
dictionary.put(word, 0);
}
in.close();
} catch (FileNotFoundException e) {
// FileNotFoundExpeption
} catch (IOException e) {
// IOExeption
}
}
Вызов:
try {
Spell.loadDictionary(getBaseContext());
} catch (IOException e) {
//IOExpeptino
}
Спасибо user - afiki
Ответы
Ответ 1
AssetManager assetManager = this.getAssets(); а ты пытаешься вызвать метод у null. try { AssetManager assetManager = this.getAssets(); InputStreamReader istream = new InputStreamReader(assetManager.open("dictionary.txt")); BufferedReader in = new BufferedReader(istream); while ((word = in.readLine()) != null) { dictionary.put(word, 0); } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }
Комментариев нет:
Отправить комментарий