다음은 버퍼링 읽기 확장 / 수정 활동에 필요한 작업을 수행하는 것입니다.
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
편집 : 귀하의 질문이 활동 이외의 방법으로 수행되는 경우 내 대답은 쓸모가 없습니다. 귀하의 질문이 단순히 자산에서 파일을 읽는 방법이라면 대답은 위의 것입니다.
업데이트 :
형식을 지정하는 파일을 열려면 간단히 다음과 같이 InputStreamReader 호출에 형식을 추가하십시오.
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
편집하다
@Stan이 의견에서 말했듯이, 내가주는 코드는 줄을 요약하지 않습니다. mLine모든 패스가 교체됩니다. 내가 쓴 이유 //process line입니다. 파일에는 일종의 데이터 (예 : 연락처 목록)가 포함되어 있으며 각 줄은 별도로 처리해야한다고 가정합니다.
어떤 종류의 처리없이 파일을 단순히로드하려는 경우 mLine각 패스를 사용 StringBuilder()하고 추가하여 각 패스 에서 합계 해야합니다.
다른 편집
@Vincent의 의견에 따르면 finally블록을 추가했습니다 .
또한 Java 7 이상 에서는 최신 Java try-with-resources의 AutoCloseable및 Closeable기능 을 사용하는 데 사용할 수 있습니다 .
문맥
의견에서 @LunarWatcher getAssets()는 classin context입니다. 따라서 외부에서 호출하는 경우이를 activity참조하고 컨텍스트 인스턴스를 활동에 전달해야합니다.
ContextInstance.getAssets();
이것은 @Maneesh의 답변에 설명되어 있습니다. 그래서 이것이 당신에게 도움이된다면 그의 대답을지지했습니다. 왜냐하면 그것은 그것을 지적한 사람이기 때문입니다.