Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

android - Read Assets file as string

I would like to read the content of a file located in the Assets as a String. For example, a text document located in src/main/assets/

Original Question
I found that this question is mostly used as a 'FAQ' for reading an assets file, therefore I summarized the question above. Below is my original question

I'm trying to read a assets file as string. I have a file in my assets folder: data.opml, and want to read it as a string.

Some things I tried:

 AssetFileDescriptor descriptor = getAssets().openFd("data.opml");
 FileReader reader = new FileReader(descriptor.getFileDescriptor());

And also:

 InputStream input = getAssets().open("data.opml");
 Reader reader = new InputStreamReader(input, "UTF-8");

But without success, so a full example would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getAssets().open() will return an InputStream. Read from that using standard Java I/O:

Java:

StringBuilder sb = new StringBuilder();
InputStream is = getAssets().open("book/contents.json");
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8 ));
String str;
while ((str = br.readLine()) != null) {
    sb.append(str);
}
br.close();

Kotlin:

val str = assets.open("book/contents.json").bufferedReader().use { it.readText() }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...