我经历了以下问题:
Load a simple text file in Android Studio
但不知怎的,我仍然遇到一个让我发疯的问题。我正在尝试加载CSV来填充Map结构。我的文件位于app / src / main / assets文件夹中,这是我的代码:
public static final String TAG = "ISO3166Database";
private static final Map<String, String> countries = new HashMap<>();
static {
BufferedReader reader = null;
IOException exception = null;
try {
InputStream iS = App.getAppContext().getAssets().open("iso-3166.txt");
reader = new BufferedReader(new InputStreamReader(iS));
String line;
while ((line = reader.readLine()) != null) {
String[] split = line.split(";");
if (split.length == 2) {
countries.put(split[0], split[1]);
}
}
} catch (IOException e) {
exception = e;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
if (exception != null) {
throw new IllegalStateException(exception);
}
}
}
public static String getAlpha2Code(String alpha3) {
if (alpha3 == null) {
return null;
}
return countries.get(alpha3.toUpperCase()).toLowerCase();
}
无论出于何种原因,我总是得到一行的NullPointer异常:
InputStream iS = App.getAppContext().getAssets().open("iso-3166.txt");
为了更简单一点,我也尝试了以下代码,在同一个地方出现完全相同的错误。
BufferedReader reader = null;
IOException exception = null;
try {
InputStream iS = App.getAppContext().getAssets().open("foo.txt");
reader = new BufferedReader(new InputStreamReader(iS));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
exception = e;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
if (exception != null) {
throw new IllegalStateException(exception);
}
}
从测试类开始,我试图用这种方法测试它:
private final String ALPHA3_COUNTRY_CODE = "CHE";
private final String ALPHA2_COUNTRY_CODE = "CH";
@Test
public void testGetAlpha2Code() throws Exception {
String alpha2 = ISO3166Database.getAlpha2Code(ALPHA3_COUNTRY_CODE);
assertEquals(alpha2, ALPHA2_COUNTRY_CODE);
}
我尝试了几种不同的方法来读取文件,但总是出现相同的错误。它一定是愚蠢的东西,但是我不能把它放在它上面。
如果有人能指出我正确的方向,我可以试着把头发留在我的头顶。
感谢您的帮助